序列化变量映射
如何序列化/反序列化 boost::program_options::variables_map?我找不到已经实现的序列化函数,并且我不知道 Variables_map 中的哪些函数可以用来提取和重新组装映射。
How do I serialize/deserialize a boost::program_options::variables_map? I can't find an already implemented serialize function, and I don't know what functions in variables_map I can use to extract and reassemble the map.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看起来您发现
boost::program_options::variables_map
派生自std::map
,因此您可以使用它的序列化(但请参阅稍后的警告)。如果唯一剩下的问题是序列化它包含的boost::any
值,那么您就差不多了。您无法序列化任意 boost::any 因为它并不真正知道如何操纵它所保存的内容。但是,如果您知道并且可以枚举应用程序使用的类型,则可以进行序列化。例如,如果您知道 boost::any 值始终是字符串或 int,那么类似的内容应该可以工作。
序列化(值为
boost::any
):反序列化(值为
boost::any
):显然,您可以使用比“int”更有效的类型标签和序列化流中的“字符串”,但这给了您基本的想法。
编辑:
boost::archive
对 const 引用很挑剔,所以我上面写的内容不能完全编译。确实如此,并且它适用于一个非常简单的测试:此代码可能存在一些问题。第一个是在
load()
中的variable_value
- 最后一条语句从boost::any
创建一个variable_value
我不太确定bool
参数做了什么(您可能需要序列化 bool
代表的任何内容)。第二个问题是,仅通过转换为std::map
引用并反序列化,您可能会或可能不会获得一致的variables_map
。反序列化为真正的std::map
然后从std::map
内容构建variables_map
会更安全。It looks like you found out that
boost::program_options::variables_map
derives fromstd::map
so you can use its serialization (but see the warning later on this). If the only remaining problem is serializing theboost::any
values it contains then you're almost there.You can't serialize an arbitrary boost::any because it doesn't really know how to manipulate what it holds. However, if you know and can enumerate the types used by your application, then serialization is possible. For example, if you know that the
boost::any
value is always a string or an int, then something like this should work.To serialize (value is a
boost::any
):To deserialize (value is a
boost::any
):Obviously you can use more efficient type tags than "int" and "string" in your serialization stream, but this gives you the basic idea.
Edit:
boost::archive
is picky about const references so what I wrote above doesn't quite compile. This does, and it worked for a very simple test:There are a couple possible issues with this code. The first is in
load()
forvariable_value
- the last statement makes avariable_value
from aboost::any
and I wasn't quite sure what thatbool
argument did (you may need to serialize whatever thatbool
represents). The second is that you may or may not get a consistentvariables_map
by just casting to astd::map
reference and deserializing. It would be safer to deserialize into a realstd::map
and then build thevariables_map
from thestd::map
contents.