如何创造一个已经解决的未来

Car*_*son 10 c++ c++11 stdasync std-future

我有一个返回std::future. 我已经在实现中添加了一个缓存,如果不需要重新计算,我想选择立即返回一个值。

我怎样才能创造一个已经解决的未来?

// Class declarations shortened to minimal example to communicate intent
class MyClass {
    Cache m_cache;

    std::future<int> foo(int arg);
}

class Cache {
    std::optional<int> get(int arg);
}

std::future<int> MyClass::foo(int arg) {
    if (auto res = m_cache.get(arg)) {
        // *res is my result
        return std::future(*res); // ????? Doesn't work
    }
    // If the cache misses, we need to calculate it
    // Fire up the ol' thread pool and get to work
    return std::launch(std::launch::async /* ommited for brevity */);
}
Run Code Online (Sandbox Code Playgroud)

我的目标是 C++20。

Art*_*yer 11

只有std::asyncstd::packaged_taskstd::promise才能创造新状态的未来。

std::promise是最简单的方法:

std::future<int> MyClass::foo(int arg) {
    if (auto res = m_cache.get(arg)) {
        // *res is my result
        std::promise<int> p;
        p.set_value(*res);
        return p.get_future();
    }
    // If the cache misses, we need to calculate it
    // Fire up the ol' thread pool and get to work
    return std::launch(std::launch::async /* ommited for brevity */);
}
Run Code Online (Sandbox Code Playgroud)
// Or with a helper function
template<typename T>
std::future<std::decay_t<T>> make_ready_future(T&& value) {
    std::promise<std::decay_t<T>> p;
    p.set_value(std::forward<T>(value));
    return p.get_future();
}

std::future<int> MyClass::foo(int arg) {
    if (auto res = m_cache.get(arg)) {
        // *res is my result
        return make_ready_future(*res);
    }
    // If the cache misses, we need to calculate it
    // Fire up the ol' thread pool and get to work
    return std::launch(std::launch::async /* ommited for brevity */);
}
Run Code Online (Sandbox Code Playgroud)