Created
August 9, 2019 09:44
-
-
Save knotman90/15920e45c9325665e0d1edd49228564c to your computer and use it in GitHub Desktop.
This file contains 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 <string> | |
#include <algorithm> | |
#include <vector> | |
#include <tuple> | |
#include <iostream> | |
#include <optional> | |
void usage(const std::string& progName) { | |
std::cout << progName << " -X FILE -P FILE -O DIRECTORY " << std::endl | |
<< "Options:" << std::endl | |
<< "-h | --help Print this help" << std::endl | |
<< "-X Path to X file" << std::endl | |
<< "-P Path to P file" << std::endl | |
<< "-O Path to output directory." << std::endl; | |
} | |
class cmdline_args_parser{ | |
public: | |
cmdline_args_parser (const int argc, char **argv){ | |
for (int i=0; i < argc; ++i) | |
tokens.push_back(std::string(argv[i])); | |
} | |
const std::optional<std::string> getCmdOption(const std::string &option) const{ | |
auto itr = std::find(tokens.begin(), tokens.end(), option); | |
if (itr != tokens.end() && ++itr != tokens.end()) | |
return std::optional(*(itr)); | |
return std::nullopt; | |
} | |
template<typename... Options> | |
const auto get_all_options(const Options... ops) const{ | |
std::vector<std::optional<std::string>> v; | |
(v.push_back(getCmdOption(ops)), ...); | |
return v; | |
} | |
bool cmdOptionExists(const std::string &option) const{ | |
return | |
std::find(tokens.begin(), tokens.end(), option) != tokens.end(); | |
} | |
template<typename... Options> | |
bool all_options_exists(const Options... opts) const{ | |
return (... && cmdOptionExists(opts)); | |
} | |
template<typename... Options> | |
bool any_options_exists(const Options... opts) const{ | |
return (... || cmdOptionExists(opts)); | |
} | |
const std::string& get_program_name() const{ return tokens[0]; } | |
private: | |
std::vector<std::string> tokens; | |
}; | |
auto process_args(const cmdline_args_parser& p){ | |
auto opts = p.get_all_options("-X","-O","-P"); | |
if(p.any_options_exists("-h", "--help") || | |
!all_of(begin(opts), end(opts), [](const auto& x ){return x;}) ) | |
{ | |
usage(p.get_program_name()); | |
return; | |
} | |
for(const auto opt : opts){ | |
std::cout<<opt.value()<<std::endl; | |
} | |
} | |
int main(int argc, char** argv){ | |
cmdline_args_parser p (argc, argv); | |
process_args(p); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment