views:

794

answers:

3

Hello,

I wanted to use boost::thread in my program, but get the follwing compiler error (Visual Studio 2005): Error 1 error C2064: term does not evaluate to a function taking 0 arguments d:...\boost_1_37_0\boost\thread\detail\thread.hpp 56

Therefore I tried to recreate the problem in a small program and modified the working Hello World example from this site.

My test code now looks like this one. Why is it not working inside a class?:

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


class HelloWorld
{
public:
    void hello();
    void entry();
};

void HelloWorld::entry()
{
    boost::thread thrd(&HelloWorld::hello);
    thrd.join();
}

void HelloWorld::hello() 
{ 
    std::cout << "Hello world, I'm a thread!" << std::endl;
} 

int main(int argc, char* argv[]) 
{ 
    HelloWorld *bla = new HelloWorld;
    bla->entry();
    return 0;
}

Thanks for your help, /mspoerr

A: 

You are passing a member function to the thread object as the function to call when the thread starts. Since the thread doesn't have the object itself, it can't call the member function. You could make the hello function static, or look at the boost::bind library to send in the object.

mch
+3  A: 

Try it like this - the boost::thread constructor is expecting a boost::function0 (which a function pointer is, but a member function pointer isn't, due to the this pointer).

void HelloWorld::entry()
{
    boost::thread thrd(boost::bind(&HelloWorld::hello,this));
    thrd.join();
}
Harper Shelby
thank you very much! It works now with your solution./mspoerr
mspoerr
Glad to help. Member function references and bind have always been a spot that confused me as well.
Harper Shelby
+1  A: 

Member functions have a this pointer as the first argument. Since there is a boost::thread constructor that accepts function arguments, you don't need to use boost::bind. This will also work:

void HelloWorld::entry()
{
    boost::thread thrd(&HelloWorld::hello,this);
    thrd.join();
}

If your function requires arguments, you can put them after the this pointer argument.