Example
#include <meta>
int main() {
struct foo {};
std::cout << std::meta::name_of(^foo); // prints foo
}
Puzzle
- Can you implement
enum_to_string
?
#include <meta>
[[nodiscard]] constexpr auto enum_to_string(auto); // TODO
enum Color { red, green, blue };
static_assert(enum_to_string(Color::red) == "red");
static_assert(enum_to_string(Color::green) == "green");
static_assert(enum_to_string(Color::blue) == "blue");
static_assert(enum_to_string(Color(42)) == "<unnamed>");
Solutions
template<class E> requires std::is_enum_v<E>
[[nodiscard]] constexpr auto enum_to_string(E value) -> std::string {
std::string result = "<unnamed>";
[:expand(std::meta::enumerators_of(^E)):] >> [&]<auto e> {
if (value == [:e:]) {
result = std::meta::name_of(e);
}
};
return result;
}