【发布时间】:2016-07-13 04:27:01
【问题描述】:
我一直在使用std::type_index 将std::unordered_map<std::type_index, MyProperty> 存储在MyClass 中。现在我想序列化(使用 boost::serialization)MyClass。编译器说struct std::type_index has no member named serialize,这表明boost::serialization 不支持std::type_index。那么问题来了,在这种情况下该怎么办?有没有人为std::type_index 提供serialize 函数?或者是否有一个不同的对象可用于我需要的这个map 的密钥,它已经是可序列化的,可以做相同类型的事情。也就是说,当我使用函数模板时:
template <typename T>
void MyClass::func(T)
{
myMap.find(std::type_index(typeid(T)));
}
这是一个缺乏支持的演示:
#include <boost/archive/text_oarchive.hpp>
#include <fstream>
#include <typeindex>
int main()
{
std::type_index myTypeIndex = typeid(double);
std::ofstream outputStream("test.txt");
boost::archive::text_oarchive outputArchive(outputStream);
outputArchive << myTypeIndex;
outputStream.close();
return 0;
}
【问题讨论】:
-
危险。前面的雷区。你会想要索引你可以构造的东西,而不是编译器构造的东西。不幸的是,您需要围绕 typeid 创建自己的多态、可序列化包装器。
-
@RichardHodges 你是说使用
std::unordered_map<std::type_index, ...>通常是个坏主意?还是仅在需要序列化时? -
不,type_index 旨在用作您正在做的索引。它只是与 boost::serialize 不兼容,因为您不控制构造。您至少必须为其提供自定义加载/存储功能。
-
@RichardHodges 我正在考虑切换到
std::unordered_map<MyEnum, ...>并提供一个函数MyEnum TypeToEnum(type_index)- 有什么问题吗? -
我认为,如果您要进行手术,我会倾向于在对整体效率和简洁性损害最小的地方进行。如果 type_index 是这项工作的最佳键类型,我会把它留在那里,并简单地编写一些自定义代码进行序列化 - 因为这只会在一个地方影响程序。
标签: c++ c++11 serialization boost boost-serialization