File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < vector>
2+ #include < string>
3+ #include < map>
4+ #include < iostream>
5+
6+ /* *
7+ https://stackoverflow.com/a/53284026/10651567
8+ this example use a class with enum member variable to mimic
9+ an enum class with methods
10+ **/
11+
12+ using namespace std ;
13+
14+ class Fruit {
15+ public:
16+ static enum Value : int {
17+ APPLE = 0 ,
18+ BANANA,
19+ COCONUT
20+ };
21+
22+ static void setupDefaultMsg () {
23+ defaultMsg[APPLE] = " It's red." ;
24+ defaultMsg[BANANA] = " It's yellow." ;
25+ defaultMsg[COCONUT] = " It's hard." ;
26+ }
27+
28+ Fruit (Value v = APPLE, std::string msg = " " ) : value(v), customMsg(msg) { }
29+ bool operator ==(Fruit a) const { return value == a.value ; }
30+ bool operator !=(Fruit a) const { return value != a.value ; }
31+
32+ std::string str () { return !customMsg.empty () ? customMsg : defaultMsg[value]; };
33+ private:
34+ Value value;
35+ std::string customMsg;
36+ static std::map<Value, std::string> defaultMsg;
37+ };
38+
39+ std::map<Fruit::Value, std::string> Fruit::defaultMsg;
40+
41+ int main (int argc, char ** argv) {
42+ Fruit::setupDefaultMsg ();
43+
44+ Fruit apple (Fruit::APPLE), banana (Fruit::BANANA);
45+
46+ cout << (apple == banana) << endl; // 0
47+ cout << apple.str () << endl; // It's red.
48+ cout << banana.str () << endl; // It's yellow.
49+
50+ return 0 ;
51+ }
You can’t perform that action at this time.
0 commit comments