目前我有这段代码:
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<>(),但这似乎有些矫枉过正。
有没有办法简化这个?
最佳答案
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。
关于c++ - Boost 的属性树中的自动类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7773260/