boost::program_options 如何重新加载值
我想从配置文件中重新加载一些值。我知道如果 variables_map
中存在值,则 po::store
不会更改值。是否有替代方案可以替代值,即使它们已经存在?
我尝试删除要从 variables_map
重新加载的值,但 po::store
无论如何都不会添加新值(即使旧值也无法访问) )。
I would like to reload some values from a configuration file. I know that po::store
will not change values if they exist in the variables_map
. Is there an alternative that does replace values even if they already exist?
I tried deleting values that I am about to reload from the variables_map
, but po::store
does not add the new values anyway (even though old ones can not be accessed either).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
P3trus 的解决方案涉及一种沮丧。这是必要的,因为
variables_map
重载std::map::operator[]
返回const variable_value &
(const 防止重新分配)。然而,在 C++11 中,我们有未重载的
std::map::at()
,因此可以直接在需要的地方执行此操作。
The solution of P3trus involves a downcast. This is necessary as
variables_map
overloads thestd::map::operator[]
returning aconst variable_value &
(const prevents reassignments).However in C++11 we have
std::map::at()
that isn't overloaded, so it is possible to do:directly where is needed.
问题是变量映射会记住哪些选项是最终的。
如果您查看源代码,您会发现以下条目。
它是variables_map的私有成员变量。
我想最简单的方法是使用新的变量映射并替换旧的。如果您需要一些旧值,或者只是想替换其中一些值,请编写自己的存储函数。您基本上使用 po::store 创建一个临时变量映射,然后按照您需要的方式更新变量映射。
Variables_map 基本上是一个 std::map,因此您可以以相同的方式访问其内容。它存储一个 po::variable_value,一种 boost::any 对象的包装器。如果你只想替换单个值,你可以使用类似的东西
注意:po 是一个命名空间别名。
The problem is that the variables map remembers which options are final.
If you look at the source you find the following entry.
It's a private member variable of the variables_map.
I guess the easiest way would be using a new variables_map and replace the old one. If you need some of the old values, or just want to replace some of them, write your own store function. You basically create a temporary variables_map with po::store and then update your variables_map the way you need it.
The variables_map is basically a std::map so you can access its content the same way. It stores a po::variable_value, kind of a wrapper around a boost::any object.If you just want to replace a single value you can use something like that
Note: po is a namespace alias.