Namespaces
Variants

std:: coroutine_traits

From cppreference.net
Utilities library
Coroutine support
Coroutine traits
coroutine_traits
(C++20)
Coroutine handle
No-op coroutines
Trivial awaitables
Range generators
(C++23)
헤더 파일에 정의됨 <coroutine>
template < class R, class ... Args >
struct coroutine_traits ;
(C++20부터)

코루틴의 반환 타입과 매개변수 타입으로부터 프라미스 타입을 결정합니다. 표준 라이브러리 구현은 유효한 한정자 ID가 타입을 나타낼 경우 promise_type R::promise_type 과 동일한 공개 접근 가능한 멤버 타입으로 제공합니다. 그렇지 않은 경우에는 해당 멤버를 포함하지 않습니다.

Program-defined specializations of coroutine_traits must define a publicly accessible nested type promise_type , otherwise the program is ill-formed.

목차

템플릿 매개변수

R - 코루틴의 반환 타입
Args - 코루틴의 매개변수 타입들, 코루틴이 비정적 멤버 함수인 경우 암시적 객체 매개변수 를 포함

중첩 타입

이름 정의
promise_type R::promise_type 이 유효한 경우, 또는 프로그램 정의 특수화에 의해 제공됨

가능한 구현

namespace detail {
template<class, class...>
struct coroutine_traits_base {};
template<class R, class... Args>
requires requires { typename R::promise_type; }
struct coroutine_traits_base <R, Args...>
{
    using promise_type = R::promise_type;
};
}
template<class R, class... Args>
struct coroutine_traits : detail::coroutine_traits_base<R, Args...> {};

참고 사항

코루틴이 비정적 멤버 함수인 경우, Args... 의 첫 번째 타입은 암시적 객체 매개변수의 타입이며, 나머지는 함수의 매개변수 타입입니다(있는 경우).

만약 std::coroutine_traits<R, Args...>::promise_type 이 존재하지 않거나 클래스 타입이 아닌 경우, 해당 코루틴 정의는 잘못된 형식입니다.

사용자는 반환 타입 수정을 피하기 위해 프로그램 정의 타입에 의존하는 coroutine_traits 의 명시적 또는 부분 특수화를 정의할 수 있습니다.

예제

#include <chrono>
#include <coroutine>
#include <exception>
#include <future>
#include <iostream>
#include <thread>
#include <type_traits>
// 아래 coroutine_traits 특수화들이 의존하는 프로그램 정의 타입
struct as_coroutine {};
// std::future<T>를 코루틴 타입으로 사용할 수 있도록 설정
// std::promise<T>를 promise 타입으로 사용하여
template<typename T, typename... Args>
    requires(!std::is_void_v<T> && !std::is_reference_v<T>)
struct std::coroutine_traits<std::future<T>, as_coroutine, Args...>
{
    struct promise_type : std::promise<T>
    {
        std::future<T> get_return_object() noexcept
        {
            return this->get_future();
        }
        std::suspend_never initial_suspend() const noexcept { return {}; }
        std::suspend_never final_suspend() const noexcept { return {}; }
        void return_value(const T& value)
            noexcept(std::is_nothrow_copy_constructible_v<T>)
        {
            this->set_value(value);
        }
        void return_value(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>)
        {
            this->set_value(std::move(value));
        }
        void unhandled_exception() noexcept
        {
            this->set_exception(std::current_exception());
        }
    };
};
// std::future<void>에도 동일하게 적용됩니다.
template<typename... Args>
struct std::coroutine_traits<std::future<void>, as_coroutine, Args...>
{
    struct promise_type : std::promise<void>
    {
        std::future<void> get_return_object() noexcept
        {
            return this->get_future();
        }
        std::suspend_never initial_suspend() const noexcept { return {}; }
        std::suspend_never final_suspend() const noexcept { return {}; }
        void return_void() noexcept
        {
            this->set_value();
        }
        void unhandled_exception() noexcept
        {
            this->set_exception(std::current_exception());
        }
    };
};
// std::future<T>와 std::future<void>에 대한 co_await 허용
// 각 co_await마다 새로운 스레드를 생성하는 단순한 방식으로
template<typename T>
auto operator co_await(std::future<T> future) noexcept
    requires(!std::is_reference_v<T>)
{
    struct awaiter : std::future<T>
    {
        bool await_ready() const noexcept
        {
            using namespace std::chrono_literals;
            return this->wait_for(0s) != std::future_status::timeout;
        }
        void await_suspend(std::coroutine_handle<> cont) const
        {
            std::thread([this, cont]
            {
                this->wait();
                cont();
            }).detach();
        }
        T await_resume() { return this->get(); }
    };
    return awaiter { std::move(future) };
}
// 우리가 구축한 인프라를 활용합니다.
std::future<int> compute(as_coroutine)
{
    int a = co_await std::async([] { return 6; });
    int b = co_await std::async([] { return 7; });
    co_return a * b;
}
std::future<void> fail(as_coroutine)
{
    throw std::runtime_error("bleah");
    co_return;
}
int main()
{
    std::cout << compute({}).get() << '\n';
    try
    {
        fail({}).get();
    }
    catch (const std::runtime_error& e)
    {
        std::cout << "error: " << e.무엇() << '\n';
    }
}

출력:

42
error: bleah