0

Currently I have this code:

if(!variables["width"].defaulted())
{
    configTree.put(treeNames["width"], variables["width"].as<int>());
}

if(!variables["height"].defaulted())
{
    configTree.put(treeNames["height"], variables["height"].as<int>());
}

if(!variables["fullscreen"].defaulted())
{
    configTree.put(treeNames["fullscreen"], variables["height"].as<int>());
}

I'm trying to simply this. The only thing stopping me is that I will in the future also have std::string variables, which means simply looping through all the values and using as() isn't going to work.

I've considered trying to use boost::any for as<>(), but that doesn't work (loads of template errors). I've also considered having a tuple with a value specifying which type it will be, then switching through that and calling the appropriate as<>(), but that seems kind of overkill.

Is there a way to simply this?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Jookia
  • 6,544
  • 13
  • 50
  • 60
  • 1
    What do you want to achieve? (It's easy to simplify if you don't want to achieve anything. Just delete all of it.) – znkr Oct 14 '11 at 20:37
  • I want to go through each variables value and insert it into the configuration tree, string or int. – Jookia Oct 14 '11 at 21:27

1 Answers1

1
template<class T> void xput(const char* name) {
    if(!variables[name].defaulted())
        configTree.put(treeNames[name], variables[name].as<T>());
}

xput<int>("width");
xput<int>("height");
xput<int>("fullscreen");
xput<std::string>("future-option");

In case you want to achieve runtime polymorphism, convert the above function to a functor and assign it to boost::function.

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220