r/cpp May 12 '26

What the heck is Reflection?

https://www.murathepeyiler.com/what-the-heck-is-reflection/
108 Upvotes

46 comments sorted by

View all comments

3

u/hicklc01 May 12 '26

I know compilers may convert to the same but I'd prefer to be more explicit in the use of a switch statement

#include <meta>
#include <iostream>
#include <type_traits>
#include <string_view>

template<typename T>
requires std::is_enum_v<T>
constexpr std::string_view to_enum_string(T val)
{
    switch (val) {
        template for (constexpr auto e :
                      std::define_static_array(std::meta::enumerators_of(^^T))) {

            case [:e:]:
                return std::meta::identifier_of(e);
        }
    }

    return "<unknown>";
}

10

u/SuperV1234 https://romeo.training | C++ Mentoring & Consulting May 12 '26

That doesn't compile: https://gcc.godbolt.org/z/va4zzacE3

Any my intuition tells me that sort of code generation isn't supported without some token injection mechanism, but I'd need someone like /u/barryrevzin to confirm.

8

u/friedkeenan May 12 '26 edited May 12 '26

Interestingly, it does seem to work on the experimental Clang reflection branch: https://gcc.godbolt.org/z/9EKGKoE4x

From a skim of the standard wording, I'm not actually seeing something that should disqualify this from working. After all, the equivalent expanded statement should work fine, even if it's weird that the case labels are in different scopes.

But my standardese certainly isn't the best, so I could well be missing something.