Last active
August 29, 2015 14:08
-
-
Save tanitanin/a6e07dd7025b0761b07e to your computer and use it in GitHub Desktop.
Command line options parser
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
#pragma once | |
#include <string> | |
#include <functional> | |
#include <vector> | |
#include <map> | |
class options { | |
public: | |
options(); | |
~options(); | |
public: | |
void add(char c, std::function<void(void)> func); | |
void add(char c, std::function<void(std::string)> func); | |
void add(const std::string str, std::function<void(void)> func); | |
void add(const std::string str, std::function<void(std::string)> func); | |
template<class Func> void add(char c, const std::string str, Func func); | |
std::vector<std::string> parse(int argc, char *argv[]); | |
private: | |
std::map<char,std::function<void(void)>> voidmapc; | |
std::map<std::string,std::function<void(void)>> voidmapstr; | |
std::map<char,std::function<void(std::string)>> argmapc; | |
std::map<std::string,std::function<void(std::string)>> argmapstr; | |
}; | |
options::options() : | |
voidmapc(), | |
voidmapstr(), | |
argmapc(), | |
argmapstr() { | |
} | |
options::~options() { | |
} | |
void options::add(char c, std::function<void(void)> func) { | |
voidmapc[c] = func; | |
} | |
void options::add(char c, std::function<void(std::string)> func) { | |
argmapc[c] = func; | |
} | |
void options::add(const std::string str, std::function<void(void)> func) { | |
voidmapstr[str] = func; | |
} | |
void options::add(const std::string str, std::function<void(std::string)> func) { | |
argmapstr[str] = func; | |
} | |
std::vector<std::string> options::parse(int argc, char *argv[]) { | |
std::vector<std::string> remains; | |
for(int i=1; i<argc; ++i) { | |
std::string str(argv[i]); | |
std::string arg = (argv[i+1] ? argv[i+1] : ""); | |
if(str[0]=='-') { | |
if(str.size()==1) continue; | |
if(str[1]=='-') { | |
if(voidmapstr[str.substr(2)]) { | |
voidmapstr[str.substr(2)](); | |
} else if(argmapstr[str.substr(2)]) { | |
argmapstr[str.substr(2)](arg); | |
++i; | |
} | |
} else { | |
if(str.size()==2) { | |
if(voidmapc[str[1]]) { | |
voidmapc[str[1]](); | |
} else if(argmapc[str[1]]) { | |
argmapc[str[1]](arg); | |
++i; | |
} | |
} else { | |
for(char c: str.substr(1)) { | |
if(voidmapc[c]) { | |
voidmapc[c](); | |
} | |
} | |
} | |
} | |
} else { | |
remains.push_back(str); | |
} | |
} | |
return remains; | |
} | |
template<class Func> | |
void options::add(char c, const std::string str, Func func) { | |
add(c,func); | |
add(str,func); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment