c++ - 将模板(没有规范)传递给 std::thread() 会产生错误:匹配错误
问题描述
所以,我的任务是用两个线程在模板中传递向量char
和。int
为什么它不能线程读取两个容器?一些推动会有所帮助。
#include <iostream>
#include <thread>
#include <vector>
template<typename T>
void check(std::vector<T> values){
for(T& it : values){
std::cout<< it <<std::endl;
}
}
int main()
{
std::vector<int> int_values = {1,2,3,4,5};
std::vector<char> char_values = {'a','b','c','d','e'};
std::thread th1(check, int_values);
std::thread th2(check, char_values);
th1.join();
th2.join();
return 0;
}
错误是:
error: no matching function for call to std::thread::thread(<unresolved overloaded function type>,std::vector<int>&)
解决方案
check
不是函数的名称,而是模板的名称。 std::thread
需要一个函数对象,所以仅仅使用是check
行不通的。
您可以使用check<int>
来指定要使用int
的check
模板的特化,或者您可以使用 lambda 并让编译器像
std::thread th1([](const auto & var) { check(var); }, std::ref(int_values));
// or even shorter
std::thread th1([&]{ check(int_values); });
推荐阅读
- android - google play 的发布前报告中的这些警告是什么?
- odoo-11 - 尝试在 Odoo 11.0 中重新连接问题
- kubernetes - kubectl get pods 返回不一致的结果
- css - 如何在浮动元素和清除元素之间放置边距?
- c - C11 附件 K:“重叠的对象”
- python - 从 sql_alchemy 数据库中删除 pandas 数据框
- python - 验证字典列表的内容
- angular - Angular:从组件中引用 EmbeddedViewRef
- sql - 如何修复 SQL 中缺少的右括号
- java - 从 Java 函数返回环境变量并在 Jenkins 中设置相同以运行构建