c++ - 为什么我不能在 std::future 参数中使用引用

标签 c++ c++11 c++14

为什么以下代码 ( on Ideone) 会给我一个错误?

#include <future>
#include <iostream>
#include <string>

int main()
{
    int foo = 0;
    bool bar = false;
    std::future<std::string> async_request = std::async(
        std::launch::async,
        [=, &foo](bool& is_pumping_request) -> std::string {
            return "str";
        },
        bar
    );
    std::cout << async_request.get() << std::endl;
}

输出:

In file included from /usr/include/c++/5/future:38:0,
                 from prog.cpp:1:
/usr/include/c++/5/functional: In instantiation of 'struct std::_Bind_simple<main()::<lambda(bool&)>(bool)>':
/usr/include/c++/5/future:1709:67:   required from 'std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...) [with _Fn = main()::<lambda(bool&)>; _Args = {bool&}; typename std::result_of<_Functor(_ArgTypes ...)>::type = std::basic_string<char>]'
prog.cpp:15:2:   required from here
/usr/include/c++/5/functional:1505:61: error: no type named 'type' in 'class std::result_of<main()::<lambda(bool&)>(bool)>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/5/functional:1526:9: error: no type named 'type' in 'class std::result_of<main()::<lambda(bool&)>(bool)>'
         _M_invoke(_Index_tuple<_Indices...>)
         ^

但是,如果我在参数列表中将bool& 更改为bool,它compiles successfully .

为什么?

最佳答案

std::thread一样,std::asyc将参数按值传递给“函数”。如果你有一个需要引用的函数,你需要用 std::ref 包装你传递给 asyc 的变量。喜欢

#include <future>
#include <iostream>
#include <string>

int main()
{
    int foo = 0;
    bool bar = false;
    std::future<std::string> async_request = std::async(
        std::launch::async,
        [=, &foo](bool& is_pumping_request) -> std::string {
            return "str";
        },
        std::ref(bar)
    );
    std::cout << async_request.get() << std::endl;
}

Live Example

如果函数采用const &,那么您需要使用std::cref

关于c++ - 为什么我不能在 std::future 参数中使用引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41041707/

相关文章:

c++ - static_casting a constexpr void* 的结果是常量表达式吗?

c++ - 是否可以使用 decltype 来确定前向声明模板类的成员函数的返回类型?

c++ - 在派生模板类中使用条件类型特征覆盖基类中的虚拟方法

c++ - 指针的元素保存为乱码

c++ - 根据 C++11 标准中的 §12.1/4,代码不应编译

raspberry-pi - 使用 C++ 在 RPi 和 Arduino 之间进行串行通信

c++ - 指向类成员的指针作为模板参数

c++ - 有没有办法确保存储在类中的 const 引用始终引用有效对象?

c++ - C++ 中有 "generics-like"功能吗?

c++ - 程序崩溃顺序排序程序