From b87aa40629593a89b2f0f5052cceb3da9ed51d7a Mon Sep 17 00:00:00 2001 From: Kris Jusiak Date: Wed, 8 May 2024 01:25:46 -0500 Subject: [PATCH] P2996 - example of `enum_to_string` via `switch-case` Problem: - P2996 doesn't support code generation yet which would be handy for the basic enum_to_string example. Solution: - Show a simple enum_to_string example with deducing this and nested switch which shows that it's possible, though, not ideal, and that it will be changed when code generation is supported. --- 2996_reflection/reflection.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/2996_reflection/reflection.md b/2996_reflection/reflection.md index cb13d1b7..64849a9d 100644 --- a/2996_reflection/reflection.md +++ b/2996_reflection/reflection.md @@ -499,6 +499,33 @@ Note that this last version has lower complexity: While the versions using an ex On Compiler Explorer: [EDG](https://godbolt.org/z/Y5va8MqzG), [Clang](https://godbolt.org/z/Kfqc77rMq). +We can even generate switch-case. For instance we can use `deducing this` with a nested switch-case. + +::: bq +```c++ +template requires std::is_enum_v +constexpr auto enum_to_string(E value) { + static constexpr auto enumerators = std::meta::enumerators_of(^E); + return [value](this auto&& self) -> std::optional { + switch (value) { + default: + if constexpr (I < std::size(enumerators) - 1) + return self.template operator()(); + else + return std::nullopt; + case [: enumerators[I] :]: + return std::meta::name_of(enumerators[I]); + } + }(); +} +``` +::: + +Note that this version optimizations depends on the compiler ability to flatten nested switch-case and it will be able to rewritten with the code generation abilities in the future versions. + +On Compiler Explorer: [Clang](https://godbolt.org/z/Mc5Yvsrxc) + +::: Many many variations of these functions are possible and beneficial depending on the needs of the client code. For example: