Skip to content

Commit 15e766c

Browse files
enum_class_with_methods.cpp
1 parent 0c24885 commit 15e766c

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

enum_class_with_methods.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

0 commit comments

Comments
 (0)