Attaching Extended Futures

This lesson discusses how one extended future can be attached to another in C++20.

The method then empowers you to attach a future to another future. It often happens that a future will be packed into another future. The job of the unwrapping constructor is to unwrap the outer future.

The proposal N3721

Before I show the first code snippet, I have to say a few words about proposal N3721. Most of this section is from the proposal on “Improvements for std::future and Related APIs”, including my examples. Strangely, the original authors frequently did not use the final get call to get the result from the future. Therefore, I added the res.get call to the examples and saved the result in a variable myResult. Additionally, I fixed a few typos.

Press + to interact
#include <future>
using namespace std;
int main() {
future<int> f1 = async([]() { return 123; });
future<string> f2 = f1.then([](future<int> f) {
return to_string(f.get()); // here .get() won't block
});
auto myResult= f2.get();
}

There is a subtle difference between the to_string(f.get()) call (line 7) and the f2.get() call in line 10. As I already mentioned in the code snippet, the first call is non-blocking/asynchronous and the ...