Код: Выделить всё
#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'
}
Код: Выделить всё
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");
|
Почему второй пример не работает?>
Подробнее здесь: https://stackoverflow.com/questions/796 ... -constexpr