Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitor<T> class implementation in c++11 and c++03?

Herb Sutter describes implementation of template Monitor class 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 class Logger:

Logger logger;
monitor< Logger > synchronizedLogger( logger ) ;

I have two questions. Why does this code do not compile in Visual Studio 2012 with c++11? Compiler says that " 'Debug' : is not a member of 'monitor' ", where Debug is a method of Logger class.

How to implement the same monitor template class with C++03 compiler using Boost library.

like image 604
belobrov.andrey Avatar asked Mar 15 '13 14:03

belobrov.andrey


1 Answers

You are likely trying to do something like monitor< Logger >::Debug(...) call. This won't work.

Your monitor can call functions try:

monitor< Logger > logger;
logger(boost::bind(&Logger::Debug, _1, "blah"));

PS: I haven't used C++11 lambdas, not to make mistakes I provided boost::bind version

edit: Dave kindly supplied that version

logger([](Logger& l){ l.Debug("blah"); });
like image 96
kassak Avatar answered Oct 18 '22 17:10

kassak