簡體   English   中英

將模板(沒有規范)傳遞給 std::thread() 會產生錯誤:<unresolved overloaded function type> 匹配錯誤</unresolved>

[英]passing template (without a specification) to an std::thread() gives error : <unresolved overloaded function type> matching Error

所以,我的任務是用兩個線程在模板中傳遞向量charint

為什么它不能線程讀取兩個容器? 一些推動會有所幫助。

#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不是 function 的名稱,它是模板的名稱。 std::thread需要一個 function object 所以僅僅使用check是行不通的。

您可以使用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); });

模板推導不適用於std::thread ,因此請使用

  std::thread th1(check<int>, int_values);
  std::thread th2(check<char>, char_values);

另一件事,你為什么在這里使用按值傳遞,我認為你應該把它改成

#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;
}

並且std::ref()是為了使您能夠通過引用傳遞,因為std::thread將所有參數復制到內部存儲中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM