gpt4 book ai didi

c++ - std::async、std::function 对象和带有 'callable' 参数的模板

转载 作者:行者123 更新时间:2023-11-30 01:15:43 25 4
gpt4 key购买 nike

#include <functional>
#include <future>

void z(int&&){}
void f1(int){}
void f2(int, double){}

template<typename Callable>
void g(Callable&& fn)
{
fn(123);
}

template<typename Callable>
std::future<void> async_g(Callable&& fn)
{
return std::async(std::launch::async, std::bind(&g<Callable>, fn));
}

int main()
{
int a = 1; z(std::move(a)); // Does not work without std::move, OK.

std::function<void(int)> bound_f1 = f1;
auto fut = async_g(bound_f1); // (*) Works without std::move, how so?
// Do I have to ensure bound_f1 lives until thread created by async_g() terminates?
fut.get();

std::function<void(int)> bound_f2 = std::bind(f2, std::placeholders::_1, 1.0);
auto fut2 = async_g(bound_f2);
// Do I have to ensure bound_f2 lives until thread created by async_g() terminates?
fut2.get();

// I don't want to worry about bound_f1 lifetime,
// but uncommenting the line below causes compilation error, why?
//async_g(std::function<void(int)>(f1)).get(); // (**)
}

问题 1. 为什么 (*) 处的调用在没有 std::move 的情况下也能正常工作?

问题 2。 因为我不明白 (*) 处的代码是如何工作的,所以出现了第二个问题。我是否必须确保每个变量 bound_f1bound_f2 都有效,直到 async_g() 创建的相应线程终止?

问题3.为什么取消注释(**)标记的行会导致编译错误?

最佳答案

简答:在模板类型推导的上下文中,类型是从以下形式的表达式中推导出来的

template <typename T>
T&& t

t 不是右值引用,而是转发引用(要查找的关键字,有时也称为通用引用)。自动类型推导也会发生这种情况

auto&& t = xxx;

转发引用的作用是它们绑定(bind)到左值和右值引用,并且只真正意味着与 std::forward<T>(t) 一起使用。将具有相同引用限定符的参数转发给下一个函数。

当您将此通用引用与左值一起使用时,为 T 推导的类型是type& ,而当您将它与右值引用一起使用时,类型将只是 type (归结为引用折叠规则)。那么现在让我们看看您的问题会发生什么。

  1. 你的 async_g使用 bound_f1 调用函数这是一个左值。为 Callable 推导的类型因此是std::function<void(int)>&并且由于您显式地将此类型传递给 g , g需要一个左值类型的参数。当您调用 bind它复制它绑定(bind)的参数,所以 fn将被复制,然后此拷贝将传递给 g .

  2. bind (和线程/异步)执行参数的复制/移动,如果您考虑一下,这是正确的做法。这样你就不必担心 bound_f1/bound_f2 的生命周期了。 .

  3. 因为您实际上将一个右值传递到对 async_g 的调用中,这次推导的类型为 Callable就是std::function<void(int)> .但是因为你把这个类型转发给了g ,它需要一个右值参数。而 fn 的类型是右值,它本身是左值并被复制到 bind 中。所以当绑定(bind)函数执行时,它会尝试调用

    void g(std::function<void(int)>&& fn)

    带有一个不是右值的参数。这就是您的错误来源。在 VS13 中,最终的错误信息是:

    Error   1   error C2664: 'void (Callable &&)' : 
    cannot convert argument 1 from 'std::function<void (int)>' to 'std::function<void (int)> &&'
    c:\program files\microsoft visual studio 12.0\vc\include\functional 1149

现在您实际上应该重新考虑使用转发引用 (Callable&&) 尝试实现的目标、需要转发多远以及参数应该在何处结束。这也需要考虑参数的生命周期。

为了克服错误,替换bind就足够了使用 lambda(总是一个好主意!)。代码变为:

template<typename Callable>
std::future<void> async_g(Callable&& fn)
{
return std::async(std::launch::async, [fn] { g(fn); });
}

这是需要最少努力的解决方案,但参数被复制到 lambda 中。

关于c++ - std::async、std::function 对象和带有 'callable' 参数的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28047592/

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