【发布时间】:2012-07-12 12:10:51
【问题描述】:
早安,
我编写了一个类来通过 boost::program_options 解析配置文件。这是我所拥有的(缩短的):
namespace nsProOp = boost::program_options;
nsProOp::variables_map m_variableMap;
nsProOp::options_description m_description;
// To add options to the variableMap, e.g. "addOption<int>("money_amount");"
template <class T>
void addOption(const std::string& option, const std::string& helpDescription = "") {
m_description.add_options()(option.c_str(), nsProOp::value<T > (), helpDescription.c_str());
}
// And this is how i actually read the file:
void ConfigFile::parse() {
std::ifstream file;
file.open(m_pathToFile.c_str());
nsProOp::store(nsProOp::parse_config_file(file, m_description, true), m_variableMap);
nsProOp::notify(m_variableMap);
}
好的,这很好用。但我希望能够再次解析同一个文件,以便我始终使用用户提供的最新条目! boost 文档中提到了“商店”:
"在 'm' 中存储在 'options' 中定义的所有选项。 如果 'm' 已经有一个选项的非默认值,该值 不会改变,即使 'options' 指定了一些值。”
所以,如果我再次调用“parse()”,什么也不会发生,因为 m_variableMap 已被填充。我尝试调用 m_variableMap.clear() 并没有解决我的问题,所以 store 只能在第一次工作。
有人给我建议吗?如果我的问题不清楚,请告诉我。谢谢!
【问题讨论】:
-
您是否考虑过使用 boost::property_tree - 它为不同格式提供了许多解析器,并且会显着减少您的代码...
标签: c++ boost boost-program-options