将参数传递给线程函数(模板)

Passing arguments to thread function (templated)

本文关键字:模板 函数 线程 参数传递      更新时间:2023-10-16

这个问题可能与为什么将对象参考参数传递给线程函数无法编译?

我遇到了一个类似的问题,但是,就我而言,函子是一个模板。

class A {
public:
  // Non template version works as expected!!.
  // void operator()(std::ostream& out){
  //    out << "hin";
  // }
  // template version doesn't. 
    template <class Ostream>
    void operator()(Ostream& out){
        out << "hin";
    }
};
int main() {
   A a;
   thread t(a, ref(cout));
   t.join();
}

GCC说:

error: no match for 'operator<<' in 'out << "hi12"'

如何解决此问题?

您正在传递std::reference_wrapper。因此,class Ostream的类型将是std::reference_wrapper,解释了错误。

template <class OstreamRef>
void operator()(OstreamRef& outRef){
    outRef.get()<< "hin";
}

这应该修复它。

使用非模板情况,当需要转换为std::ostream&时,get()被隐式调用。但是,使用模板无需转换为任何其他类型,因此将std::reference_wrapper传递给IS,因此需要明确调用get()。谢谢@JogoJapan