【问题标题】:Passing parameter to boost::thread no overloaded function takes 2 arguments将参数传递给 boost::thread 没有重载函数需要 2 个参数
【发布时间】:2013-02-21 23:27:10
【问题描述】:

从 boost::thread 文档看来,我可以通过这样做将参数传递给线程函数:

boost::thread* myThread = new boost::thread(callbackFunc, param);

但是,当我这样做时,编译器会抱怨

没有重载函数需要 2 个参数

我的代码:

#include <boost/thread/thread.hpp>
void Game::playSound(sf::Sound* s) {
    boost::thread soundThread(playSoundTask, s);
    soundThread.join();
}

void Game::playSoundTask(sf::Sound* s) {
    // do things
}

我正在使用 Ogre3d 附带的 boost 副本,我想它可能已经很老了。不过,有趣的是,我查看了 thread.hpp,它确实包含带有 2 个或更多参数的构造函数的模板。

【问题讨论】:

  • 您的第一个问题是尝试使用thread* 初始化thread 对象,但您的错误无关紧要——听起来您要么缺少#include &lt;boost/thread.hpp&gt;,要么真的使用了 旧版 Boost...
  • 你能发一个sscce吗?
  • @ildjarn,我真傻。我在描述我的代码时犯了一个错字。我将用我的实际代码和更多信息更新问题
  • Game 是类还是命名空间?
  • @RazorStorm 好的,这就解释了。我编辑了我的答案。

标签: c++ visual-c++ boost


【解决方案1】:

问题在于成员函数采用隐式的第一个参数Type*,其中Type 是类的类型。这是在类型实例上调用成员函数的机制,这意味着您必须向 boost::thread 构造函数传递一个额外的参数。您还必须将成员函数的地址作为&amp;ClassName::functionName 传递。

我做了一个编译运行的小例子,希望能说明使用:

#include <boost/thread.hpp>
#include <iostream>

struct Foo
{
  void foo(int i) 
  {
    std::cout << "foo(" << i << ")\n";
  }
  void bar()
  {
    int i = 42;
    boost::thread t(&Foo::foo, this, i);
    t.join();
  }
};

int main()
{
  Foo f;
  f.bar();
}

【讨论】:

  • @VisionIncision boost::thread(the_function, arg0, arg1, arg2, ....)。网上有很多关于这方面的帖子。
  • 嗯,好像没用。一定还有什么不对劲的地方。不管怎么说,还是要谢谢你。我会进一步调查。
猜你喜欢
  • 1970-01-01
  • 2016-12-12
  • 2011-08-09
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多