2

fooを返す関数がありますfuturefooリターン後に呼び出されるコールバックを登録しfooます。

future<int> foo() {
    promise<int> p;
    future<int> ret(p.get_future());
    thread(bind([] (promise<int> &&p) {
        this_thread::sleep_for(chrono::seconds(3));
        p.set_value(10);
    }, move(p))).detach();
    return move(ret);
}

int main()
{
    auto f = foo();
    cout << f.get() << endl;
    return 0;
}

しかしstd::bind、右辺値参照を左辺値参照として転送するため、正常にコンパイルできないようです。それを修正する方法はありますか?


promiseオブジェクトを移動するには、醜いクラスを作成する必要があります。

template<typename T>
class promise_forward {
    promise<T> promise_;

public:
    promise_forward(promise<T> &&p) : 
        promise_(move(p)) {}

    promise_forward(promise_forward<T> &&other) : 
        promise_(move(other.promise_)) {}

    operator promise<T> () {
        return move(promise_);
    }
};

future<int> foo() {
    promise<int> p;
    future<int> ret(p.get_future());
    thread(bind([] (promise<int> &&p) {
        this_thread::sleep_for(chrono::seconds(3));
        p.set_value(10);
    }, promise_forward<int>(move(p)))).detach();
    return ret;
}

int main()
{
    auto f = foo();
    cout << f.get() << endl;
    return 0;
}
4

1 に答える 1