emplate <class T>T getVariable(const string& variableName, T default_value) { if (exists(variableName) { return get(variableName) } else { return default_value; }}
However, this is an answer to a possibly incorrect question.
Assume you have server configuration file, with the following line:
port=2345
What all can go wrong? What do you expect the result to be.
- port entry is missing. Does it make sense to continue, or use a default value? Usually, no, throw an exception
- port value is unparsable. Assume a default value? Generally no, typos happen, and admin will be wondering why the server is running, but cannot be contacted. Again, throw exception.
- port value is unexpected (1234567). This is logical error, but not something configuration can determine by itself. Return, let caller work it out.
- Optionally, implement parsing as part of type, put default value in there, in case it is unable to parse, or logical error occurs, throw an exception.
IMHO, if an optional field is missing, provide default value.
If a required field is missing, throw an exception.
Also - there is boost::program_options, which solves all of the above problems already.