最終更新日時(UTC):
が更新

履歴 編集

class
<coroutine>

std::suspend_always(C++20)

namespace std {
  struct suspend_always {
    constexpr bool await_ready() const noexcept { return false; }
    constexpr void await_suspend(coroutine_handle<>) const noexcept {}
    constexpr void await_resume() const noexcept {}
  };
}

概要

コルーチンを中断させる、トリビアルAwaitable型。

メンバ関数

名前 説明 対応バージョン
await_ready コルーチンを常に中断する C++20
await_suspend コルーチン中断時に何もしない C++20
await_resume コルーチン再開時に何もしない C++20

#include <coroutine>
#include <iostream>
#include <utility>

struct task {
  struct promise_type {
    int value_;
    auto get_return_object() { return task{*this}; }
    auto initial_suspend()
    {
      return std::suspend_always{};
    }
    auto final_suspend() noexcept
    {
      return std::suspend_always{};
    }
    void return_value(int x) { value_ = x; }
    void unhandled_exception() { std::terminate(); }
  };

  using coro_handle = std::coroutine_handle<promise_type>;

  ~task()
  {
    if (coro_)
      coro_.destroy();
  }

  task(task const&) = delete;
  task(task&& rhs)
    : coro_(std::exchange(rhs.coro_, nullptr)) {}

  int get()
  {
    if (!coro_.done()) {
      coro_.resume();
    }
    return coro_.promise().value_;
  }

private:
  explicit task(promise_type& p)
    : coro_(coro_handle::from_promise(p)) {}

  coro_handle coro_;
};

task f()
{
  std::cout << "coroutine" << std::endl;
  co_return 42;
}

int main()
{
  auto c = f();
  std::cout << "main" << std::endl;
  int r = c.get();
  std::cout << "result=" << r << std::endl;
}

出力

main
coroutine
result=42

バージョン

言語

  • C++20

処理系

関連項目