将参数传递给线程函数(模板)
Passing arguments to thread function (templated)
这个问题可能与为什么将对象参考参数传递给线程函数无法编译?
我遇到了一个类似的问题,但是,就我而言,函子是一个模板。
class A {
public:
// Non template version works as expected!!.
// void operator()(std::ostream& out){
// out << "hin";
// }
// template version doesn't.
template <class Ostream>
void operator()(Ostream& out){
out << "hin";
}
};
int main() {
A a;
thread t(a, ref(cout));
t.join();
}
GCC说:
error: no match for 'operator<<' in 'out << "hi 12"'
如何解决此问题?
您正在传递std::reference_wrapper
。因此,class Ostream
的类型将是std::reference_wrapper
,解释了错误。
template <class OstreamRef>
void operator()(OstreamRef& outRef){
outRef.get()<< "hin";
}
这应该修复它。
使用非模板情况,当需要转换为std::ostream&
时,get()
被隐式调用。但是,使用模板无需转换为任何其他类型,因此将std::reference_wrapper
传递给IS,因此需要明确调用get()
。谢谢@JogoJapan
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- 如何使用模板函数的函数签名进行SFINAE
- C++浮点数据类型和字符串数据类型无法子到模板函数中
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type
- 实现一个在集合上迭代的模板函数
- 模板函数指针和lambda
- 特征:模板函数中矩阵的平面图
- 一位朋友将模板函数缩写为clang和gcc
- 模板函数调用
- C++模板函数,用于比较任何无符号整数和有符号整数
- 具有多个模板的模板函数,用于特定数据类型(如字符串)?
- 如何制作指向模板函数的指针?
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 尝试根据类中 typedef 的存在来专门化模板函数
- C++模板函数中的初始化 - 新的初始值设定项表达式列表被视为复合表达式
- 在模板函数中推导模板函数(使用C++概念)
- 对显式实例化的模板函数的未定义引用
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- C++11:模板方法的模板函数调用无法编译?