A way to declare functions in Future C++

Since C++ 20, there are Future C++ people creating sum functions that are coroutines. C++20 introduces new keywords such as co_await, co_yield, and co_return, and much more in support of a new feature called coroutines, which is a way to pause a function and run some other function, only to return later while that other function has paused itself.

With multiples of these objects, it is possible to experience asynchronisticy but without actually working with threading, this is a new C++ paradigm.

In C++, you can write a sum coroutine as follows:

struct SumTask {

	struct promise_type {

		using Handle = std::coroutine_handle<promise_type>;

		int current_value;

		SumTask get_return_object() {
			return { Handle::from_promise(*this) };
		}
		std::suspend_always initial_suspend() { return {}; }
		std::suspend_always final_suspend() noexcept { return {}; }
		void return_void() {}
		void unhandled_exception() { std::terminate(); }

		// Handle co_yield
		std::suspend_always yield_value(int value) {
			current_value = value;
			return {};
		}

		// Handle co_await
		std::suspend_always await_transform(int value) {
			current_value = value;
			return {};
		}
	};
	
	using Coroutine = promise_type::Handle;
	Coroutine coro;

	SumTask(Coroutine h) : coro(h) {}
	~SumTask() { if (coro) coro.destroy(); }

	bool resume() {
		if (!coro.done()) 
			coro.resume();
		return !coro.done();
	}

	int sum() const { return coro.promise().current_value; }
};

SumTask sum(int a, int b) {
	co_yield a + b; // Using co_yield
}

int main() {
	
	auto sumTask = sum(5, 8);

	sumTask.resume();

	std::print(std::cout, "summed value: {}", sumTask.sum());
	
	return 0;
}

Leave a comment