Ниже пример взят из p2996 Vorbatim: < /p> [code]#include #include #include #include
template requires std::is_enum_v constexpr std::string_view enum_to_string(E value) { if constexpr (Enumerable) { template for (constexpr auto e : define_static_array(enumerators_of(^^E))) if (value == [:e:]) return identifier_of(e); } return ""; }
int main() { enum Color : int; static_assert(enum_to_string(Color(0)) == ""); std::println("Color 0: {}", enum_to_string(Color(0))); // prints ''
enum Color : int { red, green, blue }; static_assert(enum_to_string(Color::red) == "red"); static_assert(enum_to_string(Color(42)) == ""); std::println("Color 0: {}", enum_to_string(Color(0))); // prints 'red' } [/code] Я не понял, почему необходимо объявить перечисление как константа шаблона вместо непосредственного вызова is_enumerable_type в Constexpr.[code]template requires std::is_enum_v constexpr std::string_view enum_to_string(E value) { if constexpr (Enumerable) { < /code> Как это: < /p> template requires std::is_enum_v constexpr std::string_view enum_to_string(E value) { if constexpr (std::meta::is_enumerable_type(^^E)) { < /code> Но он не скомпилирован в экспериментальной реализации Clang P2996: < /p> Output of x86-64 clang (experimental P2996) (Compiler #1)
:24:17: error: static assertion failed due to requirement 'enum_to_string(Color::red) == "red"' 24 | static_assert(enum_to_string(Color::red) == "red"); | [/code] https://godbolt.org/z/38enpgjoy Почему второй пример не работает?>