Created
October 12, 2017 11:39
-
-
Save stfuchs/f6e2353356fd6a02e49711e41b9ea8d4 to your computer and use it in GitHub Desktop.
Function calls from string config
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 <iostream> | |
#include <string> | |
#include <functional> | |
#include <vector> | |
#include <unordered_map> | |
std::vector<std::string> split(const std::string& value, char delim) | |
{ | |
std::vector<std::string> res; | |
std::string::size_type start = 0; | |
std::string::size_type match; | |
while ( (match = value.find(delim, start)) != std::string::npos ) | |
{ | |
res.push_back(value.substr(start, match-start)); | |
start = match + 1; | |
} | |
res.push_back(value.substr(start)); | |
return res; | |
} | |
void func1(const std::vector<std::string>& args) | |
{ | |
std::cout << "I'm f1 with "; | |
for (const auto& arg: args) { std::cout << arg << " "; } | |
std::cout << std::endl; | |
} | |
void func2(const std::vector<std::string>& args) | |
{ | |
std::cout << "I'm f2 with "; | |
for (const auto& arg: args) { std::cout << arg << " "; } | |
std::cout << std::endl; | |
} | |
class Processor | |
{ | |
public: | |
typedef std::function< void(const std::vector<std::string>&) > FunctionT; | |
Processor() | |
{ | |
lookup_["func1"] = std::bind(func1, std::placeholders::_1); | |
lookup_["func2"] = std::bind(func2, std::placeholders::_1); | |
} | |
void execute(const std::vector<std::string>& configs) | |
{ | |
for (const auto& c: configs) | |
{ | |
auto args = split(c,' '); | |
lookup_.at(args[0])(std::vector<std::string>(args.begin()+1, args.end())); | |
} | |
} | |
private: | |
std::unordered_map<std::string, FunctionT> lookup_; | |
}; | |
int main() | |
{ | |
Processor p; | |
std::vector<std::string> config={ | |
"func1 a b", | |
"func2", | |
"func1 c d", | |
}; | |
p.execute(config); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment