Reputation: 7041
I am trying to give a function pointer to my std::thread
arguments list but I get a bunch of compile errors that I don't understand (@ MSVC\14.28.29333\include\thread(43,14): error C2672: 'invoke' : fonction correspondante surchargée introuvable [overloaded function not found]
).
I could write a mcve that gives that same error.
#include <thread>
#include <vector>
template<typename T>
void worker(std::vector<T>& data_set, void(*do_something)(T&)) {
for (T& t : data_set)
(*do_something)(t);
}
template<typename T>
std::vector<T> get_data(void(*do_something)(T&), size_t sz) {
//only 1 thread as example
std::vector<T> data_set(sz);
std::thread t1(worker<T>, data_set, do_something); //compile error
t1.join();
worker<T>(data_set, do_something); //this on the other hand does compile
return data_set;
}
void do_something_int(int& i) {
i = 1;
}
void do_something_float(float& f) {
f = 2.1f;
}
void do_something_char(char& c) {
c = 'a';
}
int main(int argc, char** argv) {
auto data_set_int = get_data(&do_something_int, 100);
auto data_set_float = get_data(&do_something_float, 100);
auto data_set_char = get_data(&do_something_char, 100);
return 0;
}
Funny thing is if I call the worker in a non-threaded way everything is fine. I don't know what the compiler is expecting.
Upvotes: 3
Views: 654
Reputation: 238401
The problem is that your function accepts the argument by non-const lvalue reference. std::thread
will pass an rvalue into the funtion, and the non-const lvalue reference cannot be bound to rvalues.
In order to pass an lvalue, you must use a reference wrapper:
std::thread t1(worker<T>, std::ref(data_set), do_something);
Always be careful to ensure lifetime of the referred object when referring to automatic objects in separate threads.
Upvotes: 5