Search code examples
c++visual-studio-2010boostboost-thread

passing functor to boost::thread failed in visual studio 2010


This simple code won't compile:

#include <cstdio>
#include <boost/thread.hpp>

struct ftor{
   void operator()(){ printf("Hello"); }
};

int main()
{
      boost::thread th( ftor() );

     th.join(); //<--- error C2228: left of '.join' must have class/struct/union
}

But, following code well compiled:

 #include <cstdio>
 #include <boost/thread.hpp>

 struct ftor{
    void operator()(){ printf("Hello"); }
 };

 int main()
 {
     ftor f;
     boost::thread th( f );

     th.join(); 
 }

Q: What's problem with #1 code ?

I use visual studio 2010 .

Update: codepade http://codepad.org/r5Aok406 shows more informative error:

Line 19: error: request for member 'join' in 'th', which is of non-class type 'mythread ()(ftor (*)())'

Solution

  •   boost::thread th( ftor() );
    

    th is declared as a function that returns boost::thread, and takes a function pointer ftor(*)() as input parameter.

    To avoid this, either use C++11's new initialization syntax,

      boost::thread th{ ftor() };
    

    Or add a parathesis around the ftor().

      boost::thread th( (ftor()) );
    

    This is actually one of the well-known c++ glitches. The cause of this problem is for C compatibility.

      struct TEST;
      TEST a(); //well defined in c, a is a function that returns TEST
    

    C++ has to be compatible with C, so Test a() must be a function, but not declare a as a TEST instance and call its default constructor!