这个问题可能与 Why does passing object reference arguments to thread function fails to compile? 有关.
我遇到了类似的问题,但是,在我的例子中,仿函数是一个模板。
class A {
public:
// Non template version works as expected!!.
// void operator()(std::ostream& out){
// out << "hi\n";
// }
// template version doesn't.
template <class Ostream>
void operator()(Ostream& out){
out << "hi\n";
}
};
int main() {
A a;
thread t(a, ref(cout));
t.join();
}
海湾合作委员会说:
error: no match for 'operator<<' in 'out << "hi\012"'
我该如何解决这个问题?
最佳答案
您正在传递 std::reference_wrapper
.所以 class Ostream
的类型将是 std::reference_wrapper
这解释了错误。
template <class OstreamRef>
void operator()(OstreamRef& outRef){
outRef.get()<< "hi\n";
}
这应该可以解决它。
对于非模板情况,当它需要转换为std::ostream&
时,get()
会被隐式调用。但是,使用模板不需要转换为任何其他类型,因此 std::reference_wrapper
按原样传递,因此需要显式调用 get()
。谢谢@jogojapan
关于c++ - 将参数传递给线程函数(模板化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14035723/