c++ - Boost的Serialization如何判断多态对象的运行时类型
问题描述
我一直在阅读这个例子,它演示了 Boost 如何简单地通过强制使用这些对象的类多态调用来序列化多态对象Archive::template register_type<Dynamic_type>()
。
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
// in this program, these classes are never serialized directly but rather
// through a pointer to the base class bus_stop. So we need a way to be
// sure that the archive contains information about these derived classes.
//ar.template register_type<bus_stop_corner>();
ar.register_type(static_cast<bus_stop_corner *>(NULL));
//ar.template register_type<bus_stop_destination>();
ar.register_type(static_cast<bus_stop_destination *>(NULL));
// serialization of stl collections is already defined
// in the header
ar & stops;
}
这让我在休息日进行了四个小时的头脑风暴,讨论如何用像 C++ 这样没有反射的语言来完成这项工作,最后我一无所获。
从逻辑上讲,我假设库在调用时将一些类型信息存储在集合register_type<T>
中。然后,它尝试将存储的类型信息与从被序列化对象的运行时类型生成的类型信息进行比较。如果类型信息匹配,则该对象被向下转换为相应的类型。但是根本没有办法将对象转换为仅在 C++ 运行时才知道的类型。那么库如何将对象向下转换为其动态类型,以便可以正确(反)序列化对象?
解决方案
推荐阅读
- html - Favicon 在本地工作,但不在生产 expressjs 中
- docker - 如何从 docker 容器的主机目录访问文件?
- django - django.contrib.admin.sites.AlreadyRegistered:模型成分已经注册
- r - 在 Shiny 中创建交互式 Highchart 地图?
- .net - “Environment.Is64BitProcess”是否等于“IntPtr.Size == 8”?
- mongodb - 我将 mongoDB 的 findOneAndUpdate 与 { returnOriginal: false } 一起使用,但它不起作用
- internet-explorer - 在 Edge IE 模式下配置共享 cookie:可以使用通配符还是变量?
- pandas - 按列名中小数点前的数字合并列
- powerbi - 将 Athena 与 Power BI 连接 在数据导入完成之前,其数据源已超时
- d3.js - 条形图上的 D3 渐变填充 - 带色标