gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:16:43 26 4
gpt4 key购买 nike

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

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

但是,当我这样做时,编译器会提示

no overloaded function takes 2 arguments

我的代码:

#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 个或更多参数的构造函数的模板。

最佳答案

问题在于成员函数采用隐式第一个参数 Type*,其中 Type 是类的类型。这是在类型实例上调用成员函数的机制,意味着您必须将额外的参数传递给 boost::thread 构造函数。您还必须将成员函数的地址作为 &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();
}

关于c++ - 将参数传递给 boost::thread 没有重载函数需要 2 个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15259769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com