【问题标题】:How to thread a callable function who is method of a class如何线程化作为类方法的可调用函数
【发布时间】:2012-10-08 11:07:28
【问题描述】:

使用 MS VC++ 2012 和 Boost 库 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(boost::bind(&C::callable, bPtr->cPtr, x));这样的东西
  • @David 你的建议编译好了。经过更深入的验证,我回来了。非常感谢。

标签: c++ boost c++11 visual-studio-2012 boost-thread


【解决方案1】:

你想要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;
}

样本输出:

cPtr = 0x1a100f0
j = 42, this = 0x1a100f0

【讨论】:

  • bind 可以省去:boost::thread(&amp;C::callable, bPtr-&gt;cPtr, x) 会达到同样的效果。
  • 谢谢。你是对的,答案更新了。我不知道为什么我认为它是必要的。 (我认为因为如果您需要转换 shared_ptr 则需要它。)
猜你喜欢
  • 2011-04-19
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多