libcoro  1.0
Coroutine support library for C++20
make_awaitable.h
1 #pragma once
2 
3 #include "common.h"
4 
5 namespace coro {
6 
8 
27 template<std::invocable<> Fn>
28 class make_awaitable: public std::suspend_never {
29 public:
30 
31  static constexpr bool is_async = false;
32 
33  make_awaitable(Fn &&fn):_fn(fn) {}
34  make_awaitable(Fn &fn) : _fn(fn) {}
35 
36  auto await_resume() {
37  return _fn();
38  }
39 protected:
40  Fn &_fn;
41 };
42 
43 
44 template<std::invocable<> Fn>
45 requires coro::directly_awaitable<std::invoke_result_t<Fn> >
46 class make_awaitable<Fn> {
47 public:
48 
49  static constexpr bool is_async = true;
50 
51  make_awaitable(Fn &&fn):_awaiter(fn()) {}
52  make_awaitable(Fn &fn) :_awaiter(fn()) {}
53 
54  bool await_ready() {return _awaiter.await_ready();}
55  auto await_suspend(std::coroutine_handle<> h) {return _awaiter.await_suspend(h);}
56  decltype(auto) await_resume() {return _awaiter.await_resume();}
57 
58 protected:
59  std::invoke_result_t<Fn> _awaiter;
60 };
61 
62 template<std::invocable<> Fn>
63 requires coro::indirectly_awaitable<std::invoke_result_t<Fn> >
64 class make_awaitable<Fn> {
65 public:
66 
67  static constexpr bool is_async = true;
68 
69  make_awaitable(Fn &&fn):_awaitable(fn()),_awaiter(_awaitable.operator co_await()) {}
70  make_awaitable(Fn &fn) :_awaitable(fn()),_awaiter(_awaitable.operator co_await()) {}
71 
72  bool await_ready() {return _awaiter.await_ready();}
73  auto await_suspend(std::coroutine_handle<> h) {return _awaiter.await_suspend(h);}
74  decltype(auto) await_resume() {return _awaiter.await_resume();}
75 
76 protected:
77  std::invoke_result_t<Fn> _awaitable;
78  decltype(std::declval<std::invoke_result_t<Fn> >().operator co_await()) _awaiter;
79 };
80 
81 template<typename T, typename RetVal>
82 concept maybe_awaitable = awaitable_r<make_awaitable<coro::function<T()> >, RetVal>;
83 
84 
85 }
Converts any result to awaitable object.
main namespace
Definition: aggregator.h:8