Reputation: 2631
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?
Upvotes: 4
Views: 286
Reputation: 31952
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
Upvotes: 3