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.

Create Content
enum class
#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";
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content