Skip to content

Commit 021b844

Browse files
committed
Add example file for C++11
1 parent ad44eda commit 021b844

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

example11.x.cpp

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
#include "wise_enum.h"
2+
3+
#include <cassert>
4+
#include <iostream>
5+
6+
// Equivalent to enum Color {GREEN = 2, RED};
7+
namespace my_lib {
8+
WISE_ENUM(Color, (GREEN, 2), RED)
9+
}
10+
11+
// Equivalent to enum class MoreColor : int64_t {BLUE, BLACK = 1};
12+
WISE_ENUM_CLASS((MoreColor, int64_t), BLUE, (BLACK, 1))
13+
14+
// Inside a class, must use a different macro, but still works
15+
struct Bar {
16+
WISE_ENUM_MEMBER(Foo, BUZ)
17+
};
18+
19+
// Adapt an existing enum you don't control so it works with generic code
20+
namespace another_lib {
21+
enum class SomebodyElse { FIRST, SECOND };
22+
}
23+
WISE_ENUM_ADAPT(another_lib::SomebodyElse, FIRST, SECOND)
24+
25+
struct Blub {
26+
struct Flub {
27+
28+
int x = 0;
29+
30+
};
31+
};
32+
33+
int main() {
34+
35+
// Number of enumerations:
36+
static_assert(wise_enum::enumerators<my_lib::Color>::size == 2, "");
37+
std::cerr << "Number of enumerators: "
38+
<< wise_enum::enumerators<my_lib::Color>::size << "\n";
39+
40+
// Iterate over enums
41+
std::cerr << "Enum values and names:\n";
42+
for (auto e : wise_enum::enumerators<my_lib::Color>::range) {
43+
std::cerr << static_cast<int>(e.value) << " " << e.name << "\n";
44+
}
45+
std::cerr << "\n";
46+
47+
// Convert any enum to a string
48+
std::cerr << wise_enum::to_string(my_lib::Color::RED) << "\n";
49+
50+
// Convert any string to an optional enum
51+
auto x1 = wise_enum::from_string<my_lib::Color>("GREEN");
52+
auto x2 = wise_enum::from_string<my_lib::Color>("Greeeeeeen");
53+
54+
assert(x1.value() == my_lib::Color::GREEN);
55+
assert(!x2);
56+
57+
// Everything is constexpr, and a type trait is made available for easy use in
58+
// enable_if/tag dispatch
59+
static_assert(wise_enum::is_wise_enum<my_lib::Color>::value, "");
60+
static_assert(!wise_enum::is_wise_enum<int>::value, "");
61+
enum flub { blub, glub };
62+
static_assert(!wise_enum::is_wise_enum<flub>::value, "");
63+
// We made a regular enum wise!
64+
static_assert(wise_enum::is_wise_enum<another_lib::SomebodyElse>::value, "");
65+
66+
// Assert underlying type
67+
static_assert(
68+
std::is_same<int64_t,
69+
typename std::underlying_type<MoreColor>::type>::value,
70+
"");
71+
72+
// Full API available for adapted wise enums
73+
for (auto e : wise_enum::enumerators<another_lib::SomebodyElse>::range) {
74+
std::cerr << static_cast<int>(e.value) << " "
75+
<< wise_enum::to_string(e.value) << "\n";
76+
}
77+
78+
return 0;
79+
}

0 commit comments

Comments
 (0)