繁体   English   中英

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

[英]Passing arguments to thread function (templated)

这个问题可能与为什么传递对象引用参数到线程函数无法编译有关?

我遇到了类似的问题,但在我的情况下,仿函数是一个模板。

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

GCC说:

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()隐式调用get() 但是,使用模板不需要转换为任何其他类型,因此std::reference_wrapper按原样传递,因此需要显式调用get() 谢谢@jogojapan

暂无
暂无

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

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