Last active
November 12, 2019 23:10
-
-
Save ChunMinChang/30fd3b2c8bb7fcfea2afe465455f9764 to your computer and use it in GitHub Desktop.
An example of mapping strings and functions
This file contains hidden or 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 <assert.h> | |
#include <iostream> | |
#include <string> | |
#include <unordered_map> | |
class Player { | |
public: | |
static void DoAction(std::string action) { | |
std::string message; | |
const std::unordered_map<std::string, std::function<void()>> map = { | |
{"play", | |
[&]() { | |
if (!CAN_PLAY) { | |
message = "Cannot play"; | |
return; | |
} | |
std::cout << "do play" << std::endl; | |
}}, | |
{"pause", [&]() { | |
if (!CAN_PAUSE) { | |
message = "Cannot pause"; | |
return; | |
} | |
std::cout << "do pause" << std::endl; | |
}}}; | |
auto it = map.find(action); | |
assert(it != map.end()); | |
it->second(); | |
// log errors | |
if (!message.empty()) { | |
std::cout << message << std::endl; | |
} | |
} | |
private: | |
static const bool CAN_PLAY = true; | |
static const bool CAN_PAUSE = false; | |
}; | |
int main() { | |
Player::DoAction("play"); | |
Player::DoAction("pause"); | |
// Player::DoAction("nexttrack"); // An invalid action hitting the assertion. | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment