0

目前我有这个代码:

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>());
}

我试图简单地做到这一点。唯一阻止我的是,我将来还会有 std::string 变量,这意味着简单地循环所有值并使用 as() 是行不通的。

我考虑过尝试将 boost::any 用于 as<>(),但这不起作用(大量模板错误)。我还考虑过有一个值指定它将是哪种类型的元组,然后切换它并调用适当的 as<>(),但这似乎有点矫枉过正。

有没有办法简单地做到这一点?

4

1 回答 1

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");

如果您想实现运行时多态性,请将上述函数转换为仿函数并将其分配给 boost::function。

于 2011-10-14T21:12:38.290 回答