简体   繁体   English

将参数传递给boost :: thread没有重载函数需要2个参数

[英]Passing parameter to boost::thread no overloaded function takes 2 arguments

From the boost::thread documentation it seems that I can pass parameters to the thread function by doing this: 从boost :: thread文档看来,我可以通过执行以下操作将参数传递给线程函数:

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

However, when I do this the compiler complains that 但是,当我这样做时,编译器会抱怨

no overloaded function takes 2 arguments 没有重载函数需要2个参数

My code: 我的代码:

#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
}

I am using the copy of boost that came with Ogre3d, which I suppose could be very old. 我使用的是Ogre3d随附的boost副本,我认为它可能很旧。 Interestingly, though, I took a look at thread.hpp and it does have the templates for constructors with 2 or more parameters. 不过,有趣的是,我看了一下thread.hpp,它确实具有带有2个或更多参数的构造函数的模板。

The problem is that member functions take an implicit first parameter Type* , where Type is the type of the class. 问题在于成员函数采用隐式的第一个参数Type* ,其中Type是类的类型。 This is the mechanism by which member functions get called on instances of types, and means you have to pass an extra parameter to the boost::thread constructor. 这是在类型的实例上调用成员函数的机制,这意味着您必须将一个额外的参数传递给boost::thread构造函数。 You also have to pass the address of the member function as &ClassName::functionName . 您还必须将成员函数的地址传递为&ClassName::functionName

I have made a small compiling and running example that I hope illustrates the use: 我做了一个小的编译和运行示例,希望可以说明该用法:

#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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM