[英]passing template (without a specification) to an std::thread() gives error : <unresolved overloaded function type> matching Error
So, my task is to pass both vectors char
& int
in the template with two threads.所以,我的任务是用两个线程在模板中传递向量
char
和int
。
Why it cannot thread to reading the two containers?为什么它不能线程读取两个容器? Some push will be helpful.
一些推动会有所帮助。
#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;
}
The Error is:错误是:
error: no matching function for call to std::thread::thread(<unresolved overloaded function type>,std::vector<int>&)
check
is not the name of a function, it is the name of a template. check
不是 function 的名称,它是模板的名称。 std::thread
needs a function object so just using check
won't work. std::thread
需要一个 function object 所以仅仅使用check
是行不通的。
You can use check<int>
to specify the int
specialization of the check
template be used, or you could use a lambda and let the compiler figure it out like您可以使用
check<int>
指定要使用的check
模板的int
特化,或者您可以使用 lambda 并让编译器像
std::thread th1([](const auto & var) { check(var); }, std::ref(int_values));
// or even shorter
std::thread th1([&]{ check(int_values); });
template deduction doesn't work with std::thread
, so use模板推导不适用于
std::thread
,因此请使用
std::thread th1(check<int>, int_values);
std::thread th2(check<char>, char_values);
Another thing, why do you use pass by value here I think you should change that to be另一件事,你为什么在这里使用按值传递,我认为你应该把它改成
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
template<typename T>
void check(const std::vector<T> & values){
for(const 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>, std::ref( int_values ));
std::thread th2(check<char>, std::ref( char_values ));
th1.join();
th2.join();
return 0;
}
and std::ref()
is to enable you to pass by reference because std::thread
copies all args in an internal storage并且
std::ref()
是为了使您能够通过引用传递,因为std::thread
将所有参数复制到内部存储中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.