Hen*_*ann 2 c++ templates c++11 stdthread
我正在尝试从模板函数创建线程,为线程提供另一个模板函数。
我附加了一个出现相同错误的情况的示例。为线程提供一个非模板化的函数(即此处一个 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);
threadPool<float>(&b);
}
Run Code Online (Sandbox Code Playgroud)
使用 g++ 或 icc 编译此示例:
icc -Wall -g3 -std=c++11 -O0 -pthread
Run Code Online (Sandbox Code Playgroud)
给出以下错误消息(icc):
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)
Run Code Online (Sandbox Code Playgroud)
预先非常感谢
那是因为 justprint不是一个完整的类型。
我还没有尝试过,但是做eg&print<T>应该可以。
不相关,但不需要将指针传递给您的threadPool函数。传递(可能是常量)引用可能会更好。