C++ 如何通过调用boost::future::then()返回boost::future的值

C++ 如何通过调用boost::future::then()返回boost::future的值,c++,boost,concurrency,future,C++,Boost,Concurrency,Future,我正在尝试使用boost::future的APIthen()。我知道它会在调用后返回一个新的boost::future。我试图将此API封装在函数调用中,并返回由boost::future::then()创建的future 我得到一个坏例子如下: class CompletableFutureV2 { private: typedef const boost::function<bool(boost::future<bool> f)> HandleFunc;

我正在尝试使用
boost::future
的API
then()
。我知道它会在调用后返回一个新的
boost::future
。我试图将此API封装在函数调用中,并返回由
boost::future::then()创建的
future

我得到一个坏例子如下:

class CompletableFutureV2
{
private:
    typedef const boost::function<bool(boost::future<bool> f)> HandleFunc;

    boost::future<bool>     m_future_available;
    boost::promise<bool>    m_promise;


public:
    CompletableFutureV2() {
        m_promise = boost::promise<bool>();
        m_future_available = m_promise.get_future();
    }

    void complete(bool value) {
        m_promise.set_value(value);
    }

    boost::future<bool> then_run(HandleFunc func) {
        // return the future created by then()
        return m_future_available.then(func); // -> cause error
    }

    boost::future<bool>& get_future_available() {return m_future_available;}
};
那么,我的问题是,是否可以从函数调用返回
boost::future
?我知道
boost::future
的析构函数将被阻止,直到future就绪。所以我不想打扰
boost::future
的析构函数。我希望
then
函数将立即返回(在异步模式下不阻塞)

我猜返回值优化将帮助我将
future::then()
返回的future实例直接发送到外部左值(即,代码中的
to_finish

顺便问一下,使用
boost::future
有什么原则吗

谢谢分享

int main() {
    CompletableFutureV2 cf;

    std::thread t1 = std::thread([&cf] (){
        std::this_thread::sleep_for(std::chrono::seconds(1));
        cf.complete(true);
    });

    std::thread t2 = std::thread([&cf] () {
        boost::future<bool> to_finish = cf.then_run([] (boost::future<bool> f){
            std::cout << "finished" << std::endl;
            return true;
        });
        std::cout << "finish set handler" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(2));
    });

    t1.join();
    t2.join();
}
void testCompletableFutureV2( void ) {
    CompletableFutureV2 cf;

    std::thread t1 = std::thread([&cf] (){
        std::this_thread::sleep_for(std::chrono::seconds(1));
        cf.complete(true);
    });

    std::thread t2 = std::thread([&cf] () {
        // boost::future<bool> to_finish = cf.then_run([] (boost::future<bool> f){
        //     std::cout << "finished" << std::endl;
        //     return true;
        // });
        // get future's reference and invoke then()
        boost::future<bool> to_finish = cf.get_future_available().then( // -> ok, but not elegant
            [] (boost::future<bool> f){
            std::cout << "finished" << std::endl;
            return true;
        });
        std::cout << "finish set handler" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(2));
    });

    t1.join();
    t2.join();
}