Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <iterator>
- #include <vector>
- #include <sstream>
- #include <map>
- namespace cltools {
- typedef std::map< std::string, int(*)( std::vector< std::string > ) > cm_map;
- typedef std::pair< std::string, int(*)( std::vector< std::string > ) > cm_action;
- typedef cm_map::iterator cm_map_itr;
- typedef std::string clarg;
- typedef std::vector<clarg> clargs;
- class Commandline {
- private:
- typedef std::istream_iterator<std::string> iit;
- cm_map commands;
- bool stop = false;
- public:
- Commandline (cm_map commands) : commands ( commands ) {};
- int start_cl ( int(*init_func)() ) {
- using namespace std;
- int return_val = 0;
- int init_return_val;
- if ((init_return_val =init_func()) != 0) {
- return init_return_val;
- }
- while (!this->stop) {
- string inp;
- getline(cin, inp);
- if (inp[0] == '/') {
- inp = inp.substr(1,inp.size()-1);
- istringstream iss (inp);
- clargs cmd_args;
- copy (iit(iss), iit(), back_inserter(cmd_args));
- string cmd = cmd_args[0];
- cmd_args.erase(cmd_args.begin());
- if (commands.count( cmd ) > 0) {
- return_val = commands[cmd] ( cmd_args );
- } else {
- cout << "Unknown command '" << cmd << "'" << endl;
- }
- }
- }
- return return_val;
- }
- void stop_cl () {
- this->stop = true;
- }
- };
- }
- int action_quit (cltools::clargs);
- int action_tell (cltools::clargs);
- int action_mockerr (cltools::clargs);
- int init_cmd ();
- cltools::Commandline * cl;
- int main () {
- using namespace cltools;
- cm_map commands {
- cm_action("quit", &action_quit),
- cm_action("tell", &action_tell),
- cm_action("merr", &action_mockerr)
- };
- cl = new Commandline (commands);
- int return_val = cl->start_cl( &init_cmd );
- delete cl;
- return return_val;
- }
- int init_cmd () {
- using namespace std;
- cout << "Init it" << endl;
- return 0;
- }
- int action_quit (cltools::clargs args) {
- cl->stop_cl();
- return 0;
- }
- int action_tell (cltools::clargs args) {
- for (cltools::clarg arg : args) {
- std::cout << arg << std::endl;
- }
- return 0;
- }
- int action_mockerr (cltools::clargs) {
- using namespace std;
- cout << "Mocked some error" << endl;
- return 1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement