std::线程在模板函数外调用模板函数
std::thread calling template function out of template function
我正试图从一个模板函数中创建线程,为线程提供另一个模板功能。
我附上了一个同样错误的例子。给线程一个未模板化的函数(即这里的一个函数带有int
,一个函数带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);
}
使用g++或icc编译此示例时使用:
icc -Wall -g3 -std=c++11 -O0 -pthread
给出以下错误消息(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)
提前非常感谢
这是因为只有print
不是一个完整的类型。
我还没有试过,但做&print<T>
应该有效。
不相关,但不需要向threadPool
函数传递指针。传递一个(可能的常量)引用可能会更好。
使用此:
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::thread([value,text]() { print(value, text); });
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 成员函数调用和C++对象模型
- 使用共享指针的函数调用,其对象应为 const
- C++:编译时检查匹配的函数调用对?
- 函数调用C++中的参数太少
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 返回指向对象的指针的函数调用是否为 prvalue?
- C++ 如何重载 [] 运算符并进行函数调用
- 代码的效率. 转到和函数调用
- 是同一作用域的函数部分中的函数调用
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- 类型擦除的std::function与虚拟函数调用的开销