mspoerr
mspoerr

Reputation: 2710

boost:thread - compiler error

I wanted to use boost::thread in my program, but get the following 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. 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;
}

Upvotes: 2

Views: 4471

Answers (3)

Reputation:

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.

Upvotes: 4

Harper Shelby
Harper Shelby

Reputation: 16581

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();
}

Upvotes: 7

mch
mch

Reputation: 7393

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.

Upvotes: 0

Related Questions