std :: thread调用模板函数的模板函数

时间:2014-04-16 11:00:45

标签: c++ templates c++11 stdthread

我正在尝试使用模板函数创建线程,为线程提供另一个模板函数。

我附上了一个给出相同错误的情况的示例。为线程提供一个非模板化的函数(即这里一个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)

非常感谢您提前

3 个答案:

答案 0 :(得分:4)

那是因为print只是一个完整的类型。

我还没有尝试过,但是&print<T>应该有用。


不相关,但无需将指针传递给threadPool函数。传递(可能的常量)参考可能会更好。

答案 1 :(得分:1)

使用此:

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);
}

答案 2 :(得分:0)

尝试

std::thread([value,text]() { print(value, text); });
相关问题