Skip to content

Instantly share code, notes, and snippets.

@ChunMinChang
Last active November 12, 2019 23:10
Show Gist options
  • Save ChunMinChang/30fd3b2c8bb7fcfea2afe465455f9764 to your computer and use it in GitHub Desktop.
Save ChunMinChang/30fd3b2c8bb7fcfea2afe465455f9764 to your computer and use it in GitHub Desktop.
An example of mapping strings and functions
#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