【发布时间】:2012-12-26 03:35:18
【问题描述】:
这个问题可能与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();
}
GCC 说:
error: no match for 'operator<<' in 'out << "hi\012"'
我该如何解决这个问题?
【问题讨论】:
-
由于线程使用参数打印一些东西,它似乎隐含地假设参数是一个ostream。这里真的需要模板吗?
-
@jogojapan:我尝试将其作为函数模板的原因是我还需要使用一些来自 boost 的 ostream。 boost/iostreams 和 boost/文件系统。阅读您的评论后,我尝试使用非模板版本传递 boost::filesystem::ofstream ,并且它有效!!。但我不确定它是否也适用于所有其他 ostream。
-
它适用于从
std::ostream派生的任何东西。对于输出流,最好从std::ostream派生,除非您已经知道要使用的流类型不是从std::ostream派生的,否则我会假设采用std::ostream &参数就足够了。
标签: c++ multithreading c++11