问题描述
每当我发现自己需要在 C++ 程序中序列化对象时,我就会回到这种模式:
Whenever I find myself needing to serialize objects in a C++ program, I fall back to this kind of pattern:
以上在实践中效果很好.但是,我听说这种切换类 ID 是邪恶的,是一种反模式;在 C++ 中处理序列化的标准 OO 方式是什么?
The above works pretty well in practice. However, I've heard that this kind of switching over class IDs is evil and an antipattern; what's the standard, OO-way of handling serialization in C++?
推荐答案
使用类似 Boost Serialization 虽然绝不是标准,但(在大多数情况下)是一个编写得非常好的库,可以为您完成繁重的工作.
Using something like Boost Serialization, while by no means a standard, is a (for the most part) very well written library that does the grunt work for you.
上次我必须手动解析带有清晰继承树的预定义记录结构时,我最终使用了 带有可注册类的工厂模式(即使用键映射到(模板)创建者函数而不是大量开关函数)来尝试避免您遇到的问题.
The last time I had to manually parse a predefined record structure with a clear inheritance tree, I ended up using the factory pattern with registrable classes (i.e. Using a map of key to a (template) creator function rather than a lot of switch functions) to try and avoid the issue you were having.
编辑
上一段提到的对象工厂的基本 C++ 实现.
EDIT
A basic C++ implementation of a object factory mentioned in the above paragraph.
这篇关于C++中如何实现序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!