简体   繁体   中英

Passing arguments to thread function (templated)

This question might be related to Why does passing object reference arguments to thread function fails to compile? .

I encountered a similar problem, however, in my case the functor is a template.

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 says:

error: no match for 'operator<<' in 'out << "hi\012"'

How can I solve this problem?

You are passing a std::reference_wrapper . So the type of class Ostream will be std::reference_wrapper which explains the error.

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

This should fix it.

With a non template case, when it needs to convert to std::ostream& , the get() is implicitly called. However, with a template there is no need to convert to any other type, so the std::reference_wrapper is passed as-is and thus needs an explicit call to get() . Thanks @jogojapan

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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