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が有効で型を表す場合、 R::promise_type と同じ公開アクセス可能なメンバ型 promise_type を提供します。それ以外の場合、そのようなメンバは存在しません。

Program-defined specializations は、 coroutine_traits の公開アクセス可能なネスト型 promise_type を定義しなければならず、そうでない場合、プログラムは不適格となります。

目次

テンプレートパラメータ

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>をプロミスタイプとして使用することで。
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
(注:指定された条件により、HTMLタグ・属性は保持され、C++固有用語は翻訳されていません);
        }
        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 << "エラー: " << e.what() << '\n';
    }
}

出力:

42
エラー: bleah