Future get() 为 int 返回成员函数返回 void

问题描述

#include <functional>
#include <future>
#include <iostream>

class A
{
    public:
    int run(int a,const std::string& s)
    {
        std::cout << "a=" << a << ",s=" << s << std::endl;
        return a+1;
    }
};

int main()
{
    A a;
    auto f = std::bind(&A::run,&a,5,std::placeholders::_1);
    std::packaged_task<int(const std::string&)> pt(std::move(f));

    auto fut = std::async(std::move(pt),"test");
    /// std::cout << fut.get() << std::endl; Does not compile
    fut.get();
    return 0;
}

为什么 fut.get() 返回 void ? A::run 被定义为返回 int,因此它应该返回 int 而不是 void。

解决方法

您正在将 packaged_task 实例传递给 async,因此 future 的返回类型是基于:

std::packaged_task<R(Args...)>::operator()
void operator()( ArgTypes... args );

返回 void 的地方。

如果你想得到 packaged_task 存储的结果,你应该读取 packaged_task::get_future 返回的 future 存储的值:

A a;
auto f = std::bind(&A::run,&a,5,std::placeholders::_1);
std::packaged_task<int(const std::string&)> pt{std::move(f)};
std::future<int> fut = pt.get_future();
auto fut2 = std::async(std::move(pt),"test");
fut2.wait();   // wait until async's task is completed -> packaged_task was executed
std::cout << fut.get() << std::endl; // get result of packaged_task

Demo