-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreturn_value.cpp
More file actions
executable file
·51 lines (45 loc) · 1.45 KB
/
return_value.cpp
File metadata and controls
executable file
·51 lines (45 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// return_value.cpp : allow a coroutine to return a dynamically calculated value
// to compile use: /std:c++latest (Visual Studio 2022)
// -std=c++20 (g++)
// -std=c++20 -stdlib=libc++ (clang++)
#if defined(__clang__) && (__clang_major__ < 14) // workaround
#include <experimental/coroutine>
namespace std {
using namespace experimental;
}
#else
#include <coroutine>
#endif
#include <iostream>
template<typename T>
struct CoroCtx {
struct promise_type {
T value;
CoroCtx get_return_object() {
return CoroCtx<T>(std::coroutine_handle<promise_type>::from_promise(*this));
}
std::suspend_never initial_suspend() { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void unhandled_exception() {}
template<std::convertible_to<T> Return>
void return_value(Return &&ret) {
value = std::forward<Return>(ret);
}
/*~promise_type() {
std::cout << "CoroCtx::promise_type destroyed\n";
}*/
};
std::coroutine_handle<promise_type> h;
CoroCtx(std::coroutine_handle<promise_type> h) : h(h) {}
~CoroCtx() { h.destroy(); }
T operator()() {
return std::move(h.promise().value);
}
};
CoroCtx<int> answer(int n) {
co_return n + 1;
}
int main() {
auto a = answer(41);
std::cout << "answer(41) is: " << a() << '\n';
}