-
Notifications
You must be signed in to change notification settings - Fork 1
/
item10_perfer_using_scoped_enums.cpp
67 lines (54 loc) · 2.09 KB
/
item10_perfer_using_scoped_enums.cpp
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
#include <iostream>
#include <string>
#include <cstdint>
#include "type_name.hpp"
using namespace std;
/* C++11 version */
template<typename E>
constexpr typename std::underlying_type<E>::type _toEmType(E enumerator){
return static_cast<typename std::underlying_type<E>::type>(enumerator);
}
/* C++14 version */
template<typename E>
constexpr std::underlying_type_t<E> toEmType(E emulator) noexcept{
return static_cast<std::underlying_type_t<E>>(emulator);
}
/* C++14 auto version */
template<typename E>
constexpr auto
__toEmType(E enumerator){
return static_cast<std::underlying_type_t<E>>(enumerator);
}
int main(){
// unscoped.
// enum Color {black, white, red};
// auto white = false;
// scoped
enum class _Color{black, white, red};
auto white = false;
cout << "white in enum outer's scope : " << white;
cout << "white in enum's scope : " << static_cast<int>(_Color::white) << endl;
// Declare underlying type for scoped enum.
enum class Color:std::uint8_t{
black, white, red
};
cout << "Directly output the enumator :" << static_cast<int>(Color::white) << endl;
using UserInfo = std::tuple<std::string, std::string, std::size_t>;
UserInfo userInfo{"abc", "wz" ,1};
auto first_v = std::get<1>(userInfo);
cout << "first_v : " << first_v << endl;
auto _v = Color::black;
// get underlying type of enum type.
std::cout << "underlying type for enum Color : " << typeid(std::underlying_type<Color>::type).name() << endl;
// use toEuType function to get element type in Emulator.
std::tuple<string, string, string> profile{"trousers", "skirt", "hat"};
auto t_b = std::get<toEmType(_Color::black)>(userInfo);
cout << "trouser's brand : " << t_b << endl;
auto s_b = std::get<toEmType(_Color::white)>(userInfo);
cout << "skirt's brand : " << s_b << endl;
auto h_b = std::get<toEmType(_Color::red)>(userInfo);
cout << "hat's size : " << h_b << endl;
t_b = std::get<__toEmType(_Color::black)>(userInfo);
cout << "trouser's brand from __toEmType function : " << t_b << endl;
return 0;
}