Created
August 18, 2016 16:18
-
-
Save cjhanks/69c0e81f658d1f5e083e9e36a450fc93 to your computer and use it in GitHub Desktop.
String To Enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
#include <string> | |
using std::string; | |
namespace { | |
enum class SomeThing { | |
BLUE, | |
GREEN, | |
RED, | |
BLACK_HOLE_OF_COLOR, | |
}; | |
SomeThing | |
giveMe(string something) | |
{ | |
static const std::map<string, SomeThing> things = { | |
{ | |
"blue", | |
SomeThing::BLUE, | |
}, | |
{ | |
"green", | |
SomeThing::GREEN, | |
}, | |
{ | |
"red", | |
SomeThing::RED, | |
}, | |
}; | |
auto elem = things.find(something); | |
if (elem == things.end()) { | |
return SomeThing::BLACK_HOLE_OF_COLOR; | |
} else { | |
return elem->second; | |
} | |
} | |
void | |
doIt(string thing) | |
{ | |
using std::cerr; | |
using std::endl; | |
switch (giveMe(thing)) { | |
case SomeThing::RED: | |
cerr << "Something red\n"; | |
break; | |
case SomeThing::GREEN: | |
cerr << "Something green\n"; | |
break; | |
case SomeThing::BLUE: | |
cerr << "Something blue\n"; | |
break; | |
default: | |
cerr << "DANGER DANGER\n"; | |
break; | |
} | |
} | |
} // ns | |
int | |
main() | |
{ | |
doIt("red"); | |
doIt("green"); | |
doIt("blue"); | |
doIt("anything else"); | |
doIt("RED"); // capitilization matters | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment