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

std::thread calling template function out of template function

本文关键字:函数 调用 线程 std      更新时间:2023-10-16

我正试图从一个模板函数中创建线程,为线程提供另一个模板功能。

我附上了一个同样错误的例子。给线程一个未模板化的函数(即这里的一个函数带有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); });