I have been working on a rather simple facility: a concurrent for
loop construct that takes a list of input elements, an output vector, and a function that computes output elements out of input elements.
I have this snippet that does not compile:
template<class In, class Out>
void thread_do(net::coderodde::concurrent::queue<In>& input_queue,
Out (*process)(In in),
std::vector<Out>& output_vector)
{
// Pop the queue, process, and save result.
...
}
for (unsigned i = 0; i < thread_count; ++i)
{
thread_vector.push_back(std::thread(thread_do,
input_queue,
process,
output_vector));
}
I use -std=c++14
.
./concurrent.h:129:45: error: no matching constructor for initialization of 'std::thread' thread_vector.push_back(std::thread(thread_do, ^ ~~~~~~~~~~
However, I have no idea how to fix it. Tried to prepend &
to the thread_do
/appending <In, Out>
, yet no to avail.
You need to instantiate your function:
thread_vector.push_back(std::thread(thread_do<In, Out>, // you need to instantiate your template function
std::ref(input_queue), // pass parameters by ref
std::ref(process), // - // -
std::ref(output_vector))// - // -
);
This minimal, complete example (hint) shows you how to call a template member function in another thread.
#include <thread>
struct X
{
template<class A, class B> void run(A a, B b)
{
}
template<class A, class B>
void run_with(A a, B b)
{
mythread = std::thread(&X::run<A, B>, this, a, b);
}
std::thread mythread;
};
int main()
{
X x;
x.run_with(10, 12);
x.mythread.join();
}
Note that std::thread
's constructor is not able to auto-deduce template arguments. You have to be explicit.
来源:https://stackoverflow.com/questions/38191014/no-matching-constructor-for-initialization-of-stdthread