1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9// UNSUPPORTED: c++03, c++11, c++14, c++17
10
11#include <coroutine>
12#include <cassert>
13
14#include "test_macros.h"
15
16// This file tests, multishot, movable std::function like thing using coroutine
17// for compile-time type erasure and unerasure.
18template <typename R> struct func {
19 struct Input {R a, b;};
20
21 struct promise_type {
22 Input* I;
23 R result;
24 func get_return_object() { return {this}; }
25 std::suspend_always initial_suspend() { return {}; }
26 std::suspend_never final_suspend() noexcept { return {}; }
27 void return_void() {}
28 template <typename F>
29 std::suspend_always yield_value(F&& f) {
30 result = f(I->a, I->b);
31 return {};
32 }
33 void unhandled_exception() {}
34 };
35
36 R operator()(Input I) {
37 h.promise().I = &I;
38 h.resume();
39 R result = h.promise().result;
40 return result;
41 };
42
43 func() {}
44 func(func &&rhs) : h(rhs.h) { rhs.h = nullptr; }
45 func(func const &) = delete;
46
47 func &operator=(func &&rhs) {
48 if (this != &rhs) {
49 if (h)
50 h.destroy();
51 h = rhs.h;
52 rhs.h = nullptr;
53 }
54 return *this;
55 }
56
57 template <typename F> static func Create(F f) {
58 for (;;) {
59 co_yield f;
60 }
61 }
62
63 template <typename F> func(F f) : func(Create(f)) {}
64
65 ~func() {
66 if (h)
67 h.destroy();
68 }
69
70private:
71 func(promise_type *promise)
72 : h(std::coroutine_handle<promise_type>::from_promise(*promise)) {}
73 std::coroutine_handle<promise_type> h;
74};
75
76int Do(int acc, int n, func<int> f) {
77 for (int i = 0; i < n; ++i)
78 acc = f({acc, i});
79 return acc;
80}
81
82int main(int, char**) {
83 int result = Do(acc: 1, n: 10, f: [](int a, int b) {return a + b;});
84 assert(result == 46);
85
86 return 0;
87}
88

source code of libcxx/test/std/language.support/support.coroutines/end.to.end/multishot_func.pass.cpp