Sign in to follow this  
bcome

boost::thread(*this)

Recommended Posts

I'm trying to compile something like this:
class ThreadedClass
{
public:
    boost::thread *this_thread;

    ThreadedClass();
    ~ThreadedClass();

    void operator ()();
}
ThreadedClass::ThreadedClass()
{
    this_thread = new boost::thread(*this);
}
ThreadedClass::~ThreadedClass()
{
    if (this_thread) delete this_thread;
}
void ThreadedClass::operator ()()
{
    std::cout << "void ThreadedClass::operator ()()!";
    std::cout << std::endl;
}


I have this simplified class and the real class in the same project. The simplified class compiles just fine, yet the real one gives me:
c:\some\folder\someproject\somesourcefile.cpp(36) : error C2664: 'boost::thread::thread(const boost::function0<R> &)' :
cannot convert parameter 1 from 'Namespace::RealClass' to 'const boost::function0<R> &'
        with
        [
            R=void
        ]
        and
        [
            R=void
        ]
        Reason: cannot convert from 'Namespace::RealClass' to 'const boost::function0<R>'
        with
        [
            R=void
        ]
        No constructor could take the source type, or constructor overload resolution was ambiguous
What is wrong? Also I can't even do this:
typedef void (*ThreadFunction)();
ThreadFunction = *this;
I'm compiling under MSVC++ .net Toolkit 2003 with MSVC++ .net 2003 SE headers & libraries. Edit: line split for ease.

Share this post


Link to post
Share on other sites
You'll want to use boost::bind():
this_thread = new boost::thread(boost::bind(MyThreadFunc,this));


Quote:
typedef void (*ThreadFunction)();

ThreadFunction = *this;

Of course it won't work, this points to an instance of ThreadedClass, *not* a function. operator() doesn't make the class a function, operator() is just a normal function. Passing a class with operator() like a function will only work if the parameter is templated, ie

template<typename Func>
void dostuff(Func func)
{
func();
}

struct MyFunc
{
void operator()()
{
// do stuff
}
};

void test()
{
MyFunc myfunc;
dostuff(myfunc);
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this