如何使用将自动参数定义为引用的通用 lambda 创建线程?
例如,实现概念上与此等效的东西的正确方法是什么:
int vi = 0;
auto lambda = [](auto &v) {};
auto t = std::thread(lambda, std::ref(vi));
gcc-5.3 提示缺少类型:
/opt/gcc/el6/gcc-5.3.0/include/c++/5.3.0/functional: In instantiation of ‘struct std::_Bind_simple<main()::<lambda(auto:2&)>(std::reference_wrapper<int>)>’:
/opt/gcc/el6/gcc-5.3.0/include/c++/5.3.0/thread:137:59: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = main()::<lambda(auto:2&)>&; _Args = {std::reference_wrapper<int>}]’
testLambdaCapture.cpp:52:41: required from here
/opt/gcc/el6/gcc-5.3.0/include/c++/5.3.0/functional:1505:61: error: no type named ‘type’ in ‘class std::result_of<main()::<lambda(auto:2&)>(std::reference_wrapper<int>)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/opt/gcc/el6/gcc-5.3.0/include/c++/5.3.0/functional:1526:9: error: no type named ‘type’ in ‘class std::result_of<main()::<lambda(auto:2&)>(std::reference_wrapper<int>)>’
_M_invoke(_Index_tuple<_Indices...>)
^
作为附带问题,为什么当泛型参数像这样按值传递时它会起作用:
auto lambda = [](auto v) {};
auto t = std::thread(lambda, vi);
最佳答案
固定:
#include <thread>
int vi = 0;
auto lambda = [](auto &&v) {};
auto t = std::thread(lambda, std::ref(vi));
// this works too
auto rv = std::ref(vi);
auto t2 = std::thread(lambda, rv);
在这种情况下,auto&& 被推导出来,就好像它是一个模板参数一样。因此,实例化期间的实际类型是 const T&
或 T&&
(根据需要)。
关于c++ - 使用引用作为通用参数从通用 lambda 创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36653322/