C++ 如何对作为类方法的可调用函数执行线程

C++ 如何对作为类方法的可调用函数执行线程,c++,boost,c++11,visual-studio-2012,boost-thread,C++,Boost,C++11,Visual Studio 2012,Boost Thread,使用MS VC++2012和Boost library 1.51.0 这是我的问题的快照: struct B { C* cPtr; } struct C { void callable (int); } void function (B* bPtr, int x) { // error [1] here boost::thread* thrPtr = new boost::thread(bPtr->cPtr->callable, x) /

使用MS VC++2012和Boost library 1.51.0

这是我的问题的快照:

struct B {
    C* cPtr;
}

struct C {
    void callable (int);
}

void function (B* bPtr, int x) {
    // error [1] here
    boost::thread* thrPtr = new boost::thread(bPtr->cPtr->callable, x) 
    // error [2] here
    boost::thread* thrPtr = new boost::thread(&bPtr->cPtr->callable, x) 
}
[1] 错误C3867:'C::callable':函数调用缺少参数列表;使用“&C::callable”创建指向成员的指针


[2] 错误C2276:“&”:对所需的绑定成员函数表达式执行非法操作
boost::thread*thrPtr=new boost::thread(&C::callable,bPtr->cPtr,x)。以下是一个工作示例:

#include <sstream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>


struct C {
    void callable (int j)
    { std::cout << "j = " << j << ", this = " << this << std::endl; }
};

struct B {
    C* cPtr;
};

int main(void)
{
    int x = 42;
    B* bPtr = new B;
    bPtr->cPtr = new C;

    std::cout << "cPtr = " << bPtr->cPtr << std::endl;;

    boost::thread* thrPtr = new boost::thread(&C::callable, bPtr->cPtr, x);
    thrPtr->join();
    delete thrPtr;
}

您需要
boost::thread*thrPtr=newboost::thread(&C::callable,bPtr->cPtr,x)。以下是一个工作示例:

#include <sstream>
#include <boost/thread.hpp>
#include <boost/bind.hpp>


struct C {
    void callable (int j)
    { std::cout << "j = " << j << ", this = " << this << std::endl; }
};

struct B {
    C* cPtr;
};

int main(void)
{
    int x = 42;
    B* bPtr = new B;
    bPtr->cPtr = new C;

    std::cout << "cPtr = " << bPtr->cPtr << std::endl;;

    boost::thread* thrPtr = new boost::thread(&C::callable, bPtr->cPtr, x);
    thrPtr->join();
    delete thrPtr;
}

我认为您需要类似于
boost::thread*thrpr=newboost::thread(boost::bind(&C::callable,bPtr->cPtr,x))@David您的建议可以编译。经过更深入的验证,我回来了。非常感谢。我想您可能需要类似以下内容的复制:boost::thread*thrPtr=new boost::thread(boost::bind(&C::callable,bPtr->cPtr,x))@David您的建议可以编译。经过更深入的验证,我回来了。非常感谢。
bind
的可能副本可以省去:
boost::thread(&C::callable,bPtr->cPtr,x)
也可以达到同样的效果。谢谢。你说得对,答案更新了。我不知道为什么我认为这是必要的。(我认为这是因为如果你需要转换一个共享的ptr,
bind
可以省去:
boost::thread(&C::callable,bPtr->cPtr,x)
也可以达到同样的效果。谢谢。你说得对,答案更新了。我不知道为什么我认为这是必要的。(我认为,如果您需要转换共享的ptr,那么它是必需的。)