我正在尝试从模板函数创建线程,为线程提供另一个模板函数。
我附加了一个出现相同错误的情况的示例。为线程提供一个非模板化的函数(即此处一个 withint和一个 with float)不会导致错误。但是,由于我计划将此函数与许多不同类型一起使用,因此我不想指定模板类型。我还尝试了几种模板类型的指定(例如std::thread<T>或std::thread(function<T>),但没有成功。
问题:如何使用模板函数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); …Run Code Online (Sandbox Code Playgroud)