Mission Impossible / How to create datatypes which cannot contain invalid state
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
enum class
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
enum class Color { Red, Blue, Yellow };
std::string enum_to_string(Color color) {
switch (color) {
case Color::Red:
return "red";
case Color::Blue:
return "blue";
case Color::Yellow:
return "yellow";
}
// the compiler detects when not all cases are checked
// try it out
}
int main() {
auto background_color = Color::Red;
std::cout << enum_to_string(background_color) << "\n";
}
Enter to Rename, Shift+Enter to Preview
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content