Mission Impossible / How to create datatypes which cannot contain invalid state
adrianimboden
22.6K views
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";
}
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.