匹配错误,c++,multithreading,templates"/>

首页 > 解决方案 > 将模板(没有规范)传递给 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>&)

标签: c++multithreadingtemplates

解决方案


check不是函数的名称,而是模板的名称。 std::thread需要一个函数对象,所以仅仅使用是check行不通的。

您可以使用check<int>来指定要使用intcheck模板的特化,或者您可以使用 lambda 并让编译器像

std::thread th1([](const auto & var) { check(var); }, std::ref(int_values));
// or even shorter
std::thread th1([&]{ check(int_values); });

推荐阅读