std::async, std::函数对象和带有'callable'参数的模板

std::async, std::function object and templates with 'callable' parameter

本文关键字:std callable 参数 async 函数 对象      更新时间:2023-10-16
#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;

转发引用的作用是它们绑定到左值和右值引用,并且实际上只能与std::forward<T>(t)一起使用,以将具有相同引用限定符的参数转发到下一个函数。

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

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

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

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

    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 filesmicrosoft visual studio 12.0vcincludefunctional 1149
    

现在,您实际上应该重新考虑使用转发引用(Callable&&(要实现的目标,您需要转发多远以及参数应该在哪里结束。这还需要考虑参数的生存期。

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

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

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