1

I have a system were there will be some config file that I would like to be able to specify some settings, such as:

size: 10
message: "foo"
data: 12,12,39

I can parse these just fine as a container of key value pairs, like a std::unordered_map. However, when it comes time to actually apply these settings, I can't exactly figure out the best way to store the types or convert them as neccessary, let me explain.

I can deduce the type of the value based on the string after the : in my config file. But then I would need to store this type along side the value in my key/value pair. So I would end up with:

enum class TYPE {INT, FLOAT, VEC3, STRING, BOOL, FOO};
std::unordered_map<std::string,std::pair<TYPE,std::string>> params;

And from this, when it comes time to actually use my "value", I would need to run it through a switch statement based on the .first member of the pair, so do something like:

for(const auto& m : params)
{
    auto key = m.first;
    auto value = m.second;

    auto type = value.first;
    auto theActualValue = value.second;

    switch(type)
    {
    case TYPE::INT:
        applyAnIntSetting(key,std::stoi(theActualValue));
        break;
    case TYPE::STRING:
        applyAStringSetting(key, theActualValue);
        break;
    case TYPE::VEC3:
        vec3 val;
        /* do some string splitting etc */
        applyAVec3Setting(key,val);
        break;
    }
}

(this code is just to illustrate my point).

Is there a simpler/better way to do this? I'm sure I'm missing something.

NeomerArcana
  • 1,978
  • 3
  • 23
  • 50
  • how about a [boost::variant](http://www.boost.org/doc/libs/1_58_0/doc/html/variant.html)? – m.s. Apr 22 '15 at 08:05
  • [boost::any](http://www.boost.org/doc/libs/1_57_0/doc/html/any.html) – Paul Rooney Apr 22 '15 at 08:22
  • 1
    What you want to achieve is the purpose of lib [boost::property_tree](http://www.boost.org/doc/libs/1_58_0/doc/html/property_tree.html) – Drax Apr 22 '15 at 08:29

0 Answers0