动态存储内部配置
我一直在考虑使用The Right Way (R)
来存储我的程序的内部配置。
详细信息如下:
- 配置仅是运行时的,因此每次运行时都会生成。
- 它可以通过“项目”文件中的指令进行调整(并且应该)(该文件的读取不在这个问题的范围内)
- 它需要可扩展,即应该有一种方法可以添加新的“变量”赋值。
我对此的疑问是:
- 我应该如何开始呢?是一个 带有访问器和设置器的类 带有内部
std::map
自定义变量是一个不错的选择吗? - 有没有任何已知的“好”方法 这样做?
- 之间是否应该有区别 整数、布尔值和字符串 配置变量?
- 应该有什么不同吗 用户和内置之间 (预先存在,如我已经 想到了)变量?
谢谢!
PS:如果问题不清楚,请随时询问更多信息。
更新:哇,每个答案似乎都隐式或显式地使用了 boost。我应该提到我想避免提升(我想像现在一样探索标准库的功能)。
I've been thinking of The Right Way (R)
to store my program's internal configuration.
Here's the details:
- The configuration is runtime only, so generated each run.
- It can be adapted (and should) through directives in a "project" file (the reading of that file is not in the scope of this question)
- It needs to be extensible, ie there should be a way to add new "variables" with assignes values.
My questions about this:
- How should I begin with this? Is a
class with accessors and setters
with an internalstd::map
for
custom variables a good option? - Are there any known and "good" ways
of doing this? - Should there be a difference between
integer, boolean and string
configuration variables? - Should there be a difference at all
between user and built-in
(pre-existing as in I already
thought of them) variables?
Thanks!
PS: If the question isn't clear, feel free to ask for more info.
UPDATE: Wow, every answer seems to have implicitely or explicitly used boost. I should have mentioned I'd like to avoid boost (I want to explore the Standard libraries' capabilities as is for now).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 Boost.PropertyTree 来实现此目的。
You could use Boost.PropertyTree for this.
你可以做得比某种属性映射更糟糕(
StringMap
只是一个 typedef'd std::map)You could do worse than some kind of a property map (
StringMap
is just a typedef'd std::map)支持配置文件中的嵌套非常有用。类似 JSON 的东西。
由于参数值可以是标量、数组和嵌套参数组,因此可以将其存储在
boost::variant
的std::map
中,其值可以是标量、数组或其他递归的 std::map 。请注意,std::map 按名称排序,因此如果参数的原始配置文件顺序很重要,则还应该有参数的顺序索引。这可以通过使用boost::multi_index
来实现,该索引具有用于快速查找的有序索引或散列索引以及用于按原始配置文件顺序遍历参数的顺序索引。我还没有检查过,据我所知,增强属性图可以做到这一点。
可以将所有值存储为字符串(或数组值的字符串数组),仅在访问时将它们转换为目标类型。
It is very useful to support nesting in configuration files. Something like JSON.
As parameter values can be scalars, arrays and nested groups of parameters, it could be stored in a
std::map
ofboost::variant
's, whose value can be a scalar, array or otherstd::map
recursively. Note thatstd::map
sorts by name, so if the original config file order of parameters is important there should be a sequential index of parameters as well. This can be achieved by usingboost::multi_index
with an ordered or hashed index for fast lookup and a sequential index for traversing the parameters in the original config file order.I haven't checked, that boost property map could do that from what I've heard.
It is possible to store all values as strings (or arrays of strings for array values) converting them to the destination type only when accessing it.