c++ - 使用引用作为通用参数从通用 lambda 创建线程

标签 c++ lambda c++14

如何使用将自动参数定义为引用的通用 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/

相关文章:

c++ - 模板值参数上的 decltype 是否应该触发 SFINAE 上下文?

c++ - 关于 string.c_str() 生命周期

c++ - (a+b) >>1 是什么意思?

c++ - iphone 游戏在设备上运行。在模拟器中的特定级别崩溃

python - 为什么 help(lambda) 给出 SyntaxError : invalid syntax

c++ - 在编译时重新解释模板类型

python - 与 PyTorch 的 torch.no_grad 等效的 LibTorch 是什么?

java - 如何通过配对映射的键和值来生成字符串?

c# - 检查 IEnumerable<T> 是否有 5 个或更多匹配项

c++ - C++1y 中是否需要公共(public)类内类型定义?