std::thread参数中的函数指针.列表



我试图给我的std::thread参数列表一个函数指针,但我得到了一堆我不理解的编译错误(@MSVC14.28.29333includethread(43,14): error C2672: 'invoke' : fonction correspondante surchargée introuvable [overloaded function not found])。

我可以写一个mcve,给出同样的错误。

#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;
}
有趣的是,如果我以非线程的方式调用worker,一切都很好。我不知道编译器在期待什么。

问题是您的函数通过非const左值引用接受参数。std::thread将向函数传递一个右值,非const左值引用不能绑定到右值。

为了传递左值,必须使用引用包装器:

std::thread t1(worker<T>, std::ref(data_set), do_something);

在单独的线程中引用自动对象时,一定要小心确保被引用对象的生命周期。

最新更新