Skip to content

Instantly share code, notes, and snippets.

@IGI-111
Last active August 29, 2015 14:18
Show Gist options
  • Save IGI-111/5674bfd7a2d12c050b86 to your computer and use it in GitHub Desktop.
Save IGI-111/5674bfd7a2d12c050b86 to your computer and use it in GitHub Desktop.
Option handling
#include <string>
#include <functional>
#include <map>
#include <iostream>
#include <memory>
template <typename T> class TypedOption;
class Option
{
public:
template <typename T>
static T get(const std::string &key)
{
return (std::static_pointer_cast<TypedOption<T>>(options[key]))->getValue();
}
template <typename T>
static void put(const std::string &name,
std::function<T(const std::string&)> parser,
const std::string &value)
{
Option::options[name] = std::make_shared<TypedOption<T>>(name, parser, value);
}
private:
static std::map<std::string, std::shared_ptr<Option>> options;
};
std::map<std::string, std::shared_ptr<Option>> Option::options;
template <typename T>
class TypedOption : public Option
{
public:
TypedOption(const std::string &name,
std::function<T(const std::string&)> parser,
const std::string &value)
: value(parser(value))
{
}
inline T getValue() const { return value; }
private:
T value;
};
enum OPTION_ENUM { A = 0, B = 1, C = 2 };
int main(int argc, char *argv[])
{
Option::put<int>("Foo",
[](const std::string &val){
return std::stoi(val);
}, "3");
Option::put<OPTION_ENUM>("Bar",
[](const std::string &val){
static std::map<std::string, OPTION_ENUM> valueMap = {
{"a", A},
{"b", B},
{"c", C}
};
return valueMap[val];
}, "b");
// this will show 3
std::cout << Option::get<int>("Foo") << std::endl;
// this will show 1 (the integral value of B in the OPTION_ENUM
std::cout << Option::get<OPTION_ENUM>("Bar") << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment