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

标签 c++ multithreading c++11

这个问题可能与 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/

相关文章:

c++ - Qt toBase64 和 Linux base64 的区别

Java - 同步方法导致程序大幅减速

java - 每个应用程序一个(较大)线程池与每个应用程序组件多个(较小)线程池

c++ - 对 constexpr 函数的嵌套调用

c++ - 如何一次将多个整数传递给一个 vector ?

c++ - 设置获取元素的位置

c++ - 为什么我可以做 "delete p;",而不是 "delete (p+1);"?为什么 delete 需要左值?

c++ - 不能因为类不是多态而沮丧?

c++ - 类方法子集的延迟评估

Java Swing - 从多线程更新 View