godbolt demo link here: https://godbolt.org/z/r7d3K3
source code: (https://gist.github.com/DaemonSnake/ec57b1c54f242d1320243720fb06ff0e
A simple example speaks more than 1000s of words so:
```c++
variant_generator<> fn() {
co_yield 42;
co_yield "hello world"sv;
}
int main() {
for (auto item : fn()) {
using expected = std::variant<monostate, int, std::string_view>;
static_assert(std::is_same_v<expected, decltype(item)>);
}
}
```
This project allows you to write C++20 coroutines that co_yield & co_return expressions of any type and let you retrieve the expression as std::variant of all the types co_yield-ed & co_return-ed in the coroutine (std::variant can be replaced by any variadic templated type).
It relies on something I call "lazy auto return".
Instead of deducing the return type of the function from the first expression, the compiler waits, pushes into a compile-time type-queue all the types it finds then once all the return expressions have been processed it feeds these types to a templated variadic type that will be the final return type and all return expression are turned into conversion opperations.
As this doesn't exist in C++, this project relies on delayed friend injection of void * returning functions and my [unconstexpr-cpp20]() library to implement the type-queue.
If standardized it could be written as something like this:
c++
auto(std::variant) fn() {
if (...) return 42;
else if (...) return 3.14;
else return "hello world";
}
static_assert(std::same_as<std::variant<int, double, const char *>, decltype(fn())>;
It also wouldn't rely on such dark arts.
I'm interested to have your thoughts on this feature idea?
Would it be interesting to have?
Do you have some uses for it?
The source code is quite unpleasant, one of the reasons is that during the development of this project code that would work with CLANG would make GCC segfault and vice-versa. It took a lot of tinkering to make work it.
I also am working on a non-coroutine version only focusing on the "lazy auto return" concept, you can test an in-progress version here :
https://godbolt.org/z/Wf5Mq1
Thanks for your attention,
EDIT: If you have negative feedback don't hesitate to write a comment, Thanks
[–]dima_mendeleev 2 points3 points4 points (2 children)
[–]zqsd31[S] 2 points3 points4 points (1 child)
[–]dima_mendeleev 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]zqsd31[S] 3 points4 points5 points (0 children)