gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:06:35 27 4
gpt4 key购买 nike

为什么以下代码 ( 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com