2014-04-16 166 views
0

我想創建線程出模板函數給線程另一個模板函數。std ::線程調用模板函數出模板函數

我附加了一個給出相同錯誤的情況的expample。給線程一個非模板化的函數(即這裏有一個帶有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) 

非常感謝您提前

+0

'的std ::線程(打印,值,文本);'應該解決您的問題。 – Constructor

回答

4

這是因爲只是print不是一個完整的類型。

我還沒有嘗試過,但是在做&print<T>應該可以工作。


無關,但沒有必要將指針傳遞給您的threadPool函數。傳遞(可能的常量)引用可能會更好。

+0

這絕對有效。 – Danvil

0

嘗試

std::thread([value,text]() { print(value, text); }); 
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); 
}