I am trying to create threads out of a template function giving the thread another template function.
I have appended an expample of the situation that gives the same errors. Giving the thread a function that is not templated (ie here one with int
and one with float
) does not result in an error.
However since I plan to use this function with many different types I don't want to specify the template types. Also I have tried several specifyings of the template type (eg std::thread<T>
or std::thread(function<T>
) without any success.
Question: How can I call a template function with a std:thread
out of a template function?
The following is a minimum compiling example of the situation, in reality the templates are own classes:
#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);
}
compiling this example with g++ or icc with:
icc -Wall -g3 -std=c++11 -O0 -pthread
gives the folowing error messages (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)
Thank you very much in advance
That's because just print
is not a complete type.
I haven't tried it, but doing e.g. &print<T>
should work.
Unrelated, but there's no need to pass pointers to your threadPool
function. Passing a (possible constant) reference would probably be better.