Search code examples
c++c++20c++-coroutine

Verify that a type is a coroutine promise_type


An empty struct such as: struct promise_type{}; is not valid as a nested promise_type for the return type of a coroutine. It needs to implement initial_suspend() and others.

Is there a way to check that a type is a proper promise_type at compile time with a static_assert similar? I did not find a concept for it.

I would prefer it to fail to compile even if not taken into use yet.


Solution

  • There is no concept in the standard for determining the validity of a promise_type, but it is not difficult to define such concept using a requires-clause that requires the existence of functions with those specific names:

    template <typename T>
    concept coroutine_promise_type = requires(T& t) {
      t.get_return_object();
      t.initial_suspend();
      t.final_suspend();
      t.unhandled_exception();
      // ...
    };
    

    which can be more stringently constrained by return-type requirements.