Skip to content

Instantly share code, notes, and snippets.

@notlesh
Last active March 16, 2020 18:33
Show Gist options
  • Save notlesh/8623e223b884ad68bc8d38d78da59f51 to your computer and use it in GitHub Desktop.
Save notlesh/8623e223b884ad68bc8d38d78da59f51 to your computer and use it in GitHub Desktop.
config2.2.hpp
/// non-templated base class for all config definition types.
struct ConfigDefinitionBase
{
ConfigDefinitionBase(std::string section_,
std::string name_,
bool required_,
bool multiValued_);
virtual ~ConfigDefinitionBase();
/// subclasses should provide their default value as a string
virtual std::string defaultValueAsString() = 0;
/// subclasses should parse and store the provided input
virtual void parseValue(const std::string& input) = 0;
/// subclasess should write their parsed value (not default value) as a string
virtual std::string writeValue() = 0;
std::string section;
std::string name;
bool required = false;
bool multiValued = false;
};
// NEW
template<typename T>
struct ConfigDefinition : public ConfigDefinitionBase
{
ConfigDefinition(std::string section_,
std::string name_,
bool required_,
bool multiValued_,
nonstd::optional<T> defaultValue);
// NEW
T getValue();
// TODO: override virtual functions
// NEW
std::optional<T> parsedValue; // needs to be set when parseValue() called
};
using ConfigDefinition_ptr = std::unique_ptr<ConfigDefinitionBase>;
/// A configuration holds an ordered set of ConfigDefinitions defining the allowable values and
/// their constraints and an optional set defining overrides of those values (e.g. the results
/// of a parsed config file).
struct Configuration {
std::unordered_map<std::string, std::set<ConfigDefinition_ptr>> definitions;
std::unordered_map<std::string, ConfigDefinition_ptr>> configItems;
Configuration& addDefinition(ConfigDefinition_ptr def);
Configuration& addConfigItem(ConfigDefinition_ptr item);
// NEW
template<typename t>
getValue(string_view section, string_view name)
std::string
generateDefaultConfig();
std::string
generateOverridenConfig();
};
void defineSomeConig()
{
Configuration config;
config.addDefinition(std::make_unique<IntConfigDefinition>(
"router",
"threads",
false,
false,
4);
config.addDefinition(std::make_unique<StringConfigDefinition>(
"router",
"contact-file",
true,
false,
nullptr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment