Monitoring <T> class implementations in C ++ 11 and C ++ 03?
Herb Sutter describes the implementation of the Monitor class template in "C ++ and Beyond 2012: Herb Sutter - C ++ Concurrency":
template<class T> class monitor {
private:
mutable T t;
mutable std::mutex m;
public:
monitor( T t_ ) : t( t_ ) { }
template<typename F>
auto operator()( F f ) const -> decltype(f(t))
{ std::lock_guard<mutex> hold{m}; return f(t); }
};
I am trying to wrap my existing Logger class:
Logger logger;
monitor< Logger > synchronizedLogger( logger ) ;
I have two questions. Why is this code not compiling in Visual Studio 2012 using C ++ 11? The compiler says that “Debug”: is not a member of the “monitor”, where Debug is a method of the Logger class.
How to implement the same template template with the C ++ 03 compiler using the Boost library.
+5
2 answers
You are probably trying to make something like a call monitor< Logger >::Debug(...). This will not work.
Your monitor may call functions. Try:
monitor< Logger > logger;
logger(boost::bind(&Logger::Debug, _1, "blah"));
PS: ++ 11 lambdas, , boost:: bind version
edit:
logger([](Logger& l){ l.Debug("blah"); });
+8
. <T> ++ 03 Boost .
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/locks.hpp>
#include <boost/utility/result_of.hpp>
template<class T> class monitor
{
private:
mutable T& t;
mutable boost::mutex m;
public:
monitor( T& t_ ) : t( t_ )
{
}
template< typename F >
typename boost::result_of< F() >::type operator()( F f ) const
{
boost::lock_guard< boost::mutex > hold( m );
return f( t );
}
};
( ..), Mok ILogger . Google mock , .
ILogger * mockedLogger = new MockedLogger();
monitor< ILogger > synchronizedLogger( *mockedLogger ) ;
synchronizedLogger( boost::bind( &ILogger::Debug, _1, "blah" ) );
0