C++ std::在模板函数外调用模板函数的线程

C++ std::在模板函数外调用模板函数的线程,c++,templates,c++11,stdthread,C++,Templates,C++11,Stdthread,我试图用一个模板函数创建线程,并给线程另一个模板函数 我已经附加了一个给出相同错误的情况的示例。给线程一个未模板化的函数(这里一个是int函数,一个是float函数)不会导致错误。 但是,由于我计划将此函数用于许多不同的类型,因此我不想指定模板类型。我还尝试了几种模板类型的指定,例如std::thread或std::threadfunction,但没有成功 问题:如何使用模板函数的std:thread调用模板函数 以下是这种情况的最低编译示例,实际上模板是自己的类: #include <t

我试图用一个模板函数创建线程,并给线程另一个模板函数

我已经附加了一个给出相同错误的情况的示例。给线程一个未模板化的函数(这里一个是int函数,一个是float函数)不会导致错误。 但是,由于我计划将此函数用于许多不同的类型,因此我不想指定模板类型。我还尝试了几种模板类型的指定,例如std::thread或std::threadfunction,但没有成功

问题:如何使用模板函数的std:thread调用模板函数

以下是这种情况的最低编译示例,实际上模板是自己的类:

#include <thread>
#include <string>
#include <iostream>

template<class T>
void print(T* value, std::string text)
{
   std::cout << "value: " << *value << std::endl;
   std::cout << text << std::endl;
}

template<class T>
void threadPool(T* value)
{
   std::string text = "this is a text with " + std::to_string(*value);
   std::thread(&print, value, text);
}

int main(void)
{
   unsigned int a = 1;
   float b = 2.5;
   threadPool<unsigned int>(&a);
   threadPool<float>(&b);
}
给出以下错误消息:

test.cpp(17): error: no instance of constructor "std::thread::thread" matches the argument list
        argument types are: (<unknown-type>, unsigned int *, std::string)
    std::thread(&print, value, text);
    ^
      detected during instantiation of "void threadPool(T *) [with T=unsigned int]" at line 24

test.cpp(17): error: no instance of constructor "std::thread::thread" matches the argument list
        argument types are: (<unknown-type>, float *, std::string)
    std::thread(&print, value, text);
    ^
      detected during instantiation of "void threadPool(T *) [with T=float]" at line 25

compilation aborted for test.cpp (code 2)
提前非常感谢

这是因为“仅打印”并不是一种完整的类型

我还没有试过,但做例如和打印应该可以

不相关,但不需要向threadPool函数传递指针。传递一个可能的常量引用可能会更好。

这是因为just print不是一个完整的类型

我还没有试过,但做例如和打印应该可以

不相关,但不需要向threadPool函数传递指针。传递一个可能的常量引用可能会更好。

试试看

std::thread([value,text]() { print(value, text); });
试一试

使用以下命令:

template<class T>
void threadPool(T* value)
{
   std::string text = "this is a text with " + std::to_string(*value);
   std::thread(&print<T>, value, text);
}
使用以下命令:

template<class T>
void threadPool(T* value)
{
   std::string text = "this is a text with " + std::to_string(*value);
   std::thread(&print<T>, value, text);
}
标准::线程和打印、值、文本;应该可以解决您的问题。std::线程和打印、值、文本;应该能解决你的问题。