【问题标题】:boost multiple calls to class method提升对类方法的多次调用
【发布时间】:2011-08-06 00:23:30
【问题描述】:

在 boost::thread 中是否可以调用类方法而无需使类可调用并像调用类方法一样实现 void operator()()

   for(int i=0;i<5;i++)
    boost::thread worker(myclass.myfunc,i,param2);

我收到一个错误&lt;unresolved overloaded function type&gt;

其实我更想知道同样的 zi::thread

【问题讨论】:

    标签: c++ multithreading boost callable


    【解决方案1】:

    boost::thread 不需要任何特别的东西,它会完全按照你的意愿工作(减去语法错误):

    for (int i = 0; i != 5; ++i)
        boost::thread worker(&myclass::myfunc, myclassPointer, i, param2);
    

    来自boost.thread docs

    template &lt;class F,class A1,class A2,...&gt;
    thread(F f,A1 a1,A2 a2,...);

    效果:好像thread(boost::bind(f, a1, a2, ...))。因此,f 和每个aN 都被复制到内部存储中以供新线程访问。

    【讨论】:

    • 我认为这只有在 myclass::myfunc 是静态成员函数时才有效。您必须传递类的对象才能调用类成员函数。
    • @msh :没错,就像你对 boost.bind 所做的那样。不知道你在做什么......
    • 我想说,如果 myclass::myfunc 不是静态成员函数(这赢了),你不能用作 boost::thread worker(&myclass::myfunc, i, param2) '不编译)。
    【解决方案2】:

    对于 boost::thread,您可以使用 boost::bind 调用类成员函数。

    myclass obj;
    for(int i=0;i<5;i++)
            boost::thread worker(boost::bind(&myclass::myfunc,&obj,i,param2));
    

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 2019-10-22
      • 2020-11-30
      • 2013-10-22
      • 1970-01-01
      • 2015-12-20
      • 2023-03-13
      • 1970-01-01
      • 2012-11-13
      相关资源
      最近更新 更多