-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathReflection_00_Compiler_Explorer.txt
More file actions
67 lines (59 loc) · 1.84 KB
/
Copy pathReflection_00_Compiler_Explorer.txt
File metadata and controls
67 lines (59 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// =====================================================================================
// Reflection_00_Compiler_Explorer.txt
// =====================================================================================
#include <meta>
#include <optional>
#include <print>
#include <string_view>
#include <type_traits>
template<typename E>
concept isEnum = std::is_enum_v<E>;
template<isEnum E, bool Enumerable = std::meta::is_enumerable_type(^^E)>
constexpr std::string_view enum_to_string(E value)
{
if constexpr (Enumerable)
{
template for (constexpr auto e : std::define_static_array(std::meta::enumerators_of(^^E)))
{
if (value == [:e:])
{
return std::meta::identifier_of(e);
}
}
}
return "<unnamed>";
}
template<isEnum E, bool Enumerable = std::meta::is_enumerable_type(^^E)>
constexpr std::optional<E> string_to_enum(std::string_view name)
{
if constexpr (Enumerable)
{
template for (constexpr auto e : std::define_static_array(std::meta::enumerators_of(^^E)))
{
if (name == std::meta::identifier_of(e))
{
return [:e:];
}
}
}
return std::nullopt;
}
int main()
{
enum class Color : int
{
red,
green,
blue
};
static_assert(enum_to_string(Color::red) == "red");
static_assert(enum_to_string(Color(42)) == "<unnamed>");
static_assert(string_to_enum<Color>("green") == Color::green);
static_assert(!string_to_enum<Color>("nope").has_value());
std::println("Color::red -> {}", enum_to_string(Color::red));
std::println("\"blue\" -> {}", ( int ) *string_to_enum<Color>("blue"));
std::println("\"nope\" -> {}", string_to_enum<Color>("nope").has_value());
}
// =====================================================================================
// End-of-File
// =====================================================================================