eager.hpp

1
2
3
4
5
6
7
#pragma once


#include <felspar/coro/task.hpp>


namespace felspar::coro {

Immediately launch a single coroutine

11
12
13
14
15
16
    template<typename Task = task<void>>
    class eager {
      public:
        using task_type = Task;
        using promise_type = typename task_type::promise_type;
        using handle_type = typename promise_type::handle_type;

Start a task immediately

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
        eager() {}
        explicit eager(task_type t) { post(std::move(t)); }
        template<typename... PArgs, typename... MArgs>
        void post(task_type (*f)(PArgs...), MArgs &&...margs) {
            static_assert(sizeof...(PArgs) == sizeof...(MArgs));
            post(f(std::forward<MArgs>(margs)...));
        }
        template<typename N, typename... PArgs, typename... MArgs>
        void post(N &o, task_type (N::*f)(PArgs...), MArgs &&...margs) {
            static_assert(sizeof...(PArgs) == sizeof...(MArgs));
            post((o.*f)(std::forward<MArgs>(margs)...));
        }
        void post(task_type t) {
            t.start();
            coro = t.release();
        }

Lifetime

Return true if the task is already done

41
        bool done() const noexcept { return coro and coro.done(); }

Release the held task so it can be co_awaited

44
        auto release() && { return task_type(std::move(coro)); }

Destroy the contained coroutine

47
48
49
50
51
52
53
54
55
56
57
        auto destroy() {
            if (auto h = coro.release(); h) { h.destroy(); }
        }


      private:
        handle_type coro;
    };


}