-
Notifications
You must be signed in to change notification settings - Fork 16
/
enum_class_with_methods.cpp
51 lines (40 loc) · 1.24 KB
/
enum_class_with_methods.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
#include <vector>
#include <string>
#include <map>
#include <iostream>
/**
https://stackoverflow.com/a/53284026/10651567
this example use a class with enum member variable to mimic
an enum class with methods
**/
using namespace std;
class Fruit {
public:
static enum Value : int {
APPLE = 0,
BANANA,
COCONUT
};
static void setupDefaultMsg() {
defaultMsg[APPLE] = "It's red.";
defaultMsg[BANANA] = "It's yellow.";
defaultMsg[COCONUT] = "It's hard.";
}
Fruit(Value v = APPLE, std::string msg = "") : value(v), customMsg(msg) { }
bool operator==(Fruit a) const { return value == a.value; }
bool operator!=(Fruit a) const { return value != a.value; }
std::string str() { return !customMsg.empty() ? customMsg : defaultMsg[value]; };
private:
Value value;
std::string customMsg;
static std::map<Value, std::string> defaultMsg;
};
std::map<Fruit::Value, std::string> Fruit::defaultMsg;
int main(int argc, char** argv) {
Fruit::setupDefaultMsg();
Fruit apple(Fruit::APPLE), banana(Fruit::BANANA);
cout << (apple == banana) << endl; // 0
cout << apple.str() << endl; // It's red.
cout << banana.str() << endl; // It's yellow.
return 0;
}