Skip to content

Latest commit

 

History

History
57 lines (40 loc) · 1.26 KB

361.md

File metadata and controls

57 lines (40 loc) · 1.26 KB
Info

Example

#include <meta>

int main() {
    struct foo {};
    std::cout << std::meta::name_of(^foo); // prints foo
}

https://godbolt.org/z/Y8a9bWvea

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>");

https://godbolt.org/z/3nEqWbv8f

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;
}

https://godbolt.org/z/dsMTTxqTW