Namespaces
Variants
Views
Actions

Coroutines (C++20)

From cppreference.com
< cpp‎ | language
Revision as of 06:37, 21 March 2019 by Cubbi (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
 
 
C++ language
General topics
Flow control
Conditional execution statements
if
Iteration statements (loops)
for
range-for (C++11)
Jump statements
Functions
Function declaration
Lambda function expression
inline specifier
Dynamic exception specifications (until C++17*)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
Specifiers
const/volatile
decltype (C++11)
auto (C++11)
constexpr (C++11)
consteval (C++20)
constinit (C++20)
Storage duration specifiers
Initialization
Expressions
Alternative representations
Literals
Boolean - Integer - Floating-point
Character - String - nullptr (C++11)
User-defined (C++11)
Utilities
Attributes (C++11)
Types
typedef declaration
Type alias declaration (C++11)
Casts
Memory allocation
Classes
Class-specific function properties
explicit (C++11)
static

Special member functions
Templates
Miscellaneous
 
 

A coroutine is a function that can suspend execution to be resumed later. Coroutines are stackless: they suspend execution by returning to the caller.

A function is a coroutine if its definition does any of the following:

  • uses the keyword co_return for its return statement
  • uses the keyword co_yield to suspend execution with a value
generator<int> gen(int next, int inc = 1) {
  for(;;) {
    co_yield next;
    next += inc;
  }
}
  • uses the co_await operator or the co_await form of of range-for loop
task<int> f();
task<void> g1() {
  int i = co_await f();
  std::cout << "f() => " << i << '\n';
}
task<void> g2() {
  for co_await (auto&& n : gen()) 
    std::cout << "generator yielded " << n << '\n';
}

Restrictions

Coroutines cannot use variadic arguments, plain return statements, or placeholder return types (auto or Concept).

Constexpr functions, constructors, destructors, and the main function cannot be coroutines.

Explanation