问题描述
我希望从 is_bitwise_serializable trait 序列化类如下(没有序列化函数):
I expect from is_bitwise_serializable trait to serialize class like following (without serialize function):
class A { int a; char b; };
BOOST_IS_BITWISE_SERIALIZABLE(A);
A a{2, 'x'};
some_archive << a; // serializes a bitwisely
我想知道,为什么需要为 bitwise_serializable 类提供序列化功能?
I wonder, why is there a need to provide serialize function for bitwise_serializable class?
推荐答案
来自文档:
一些简单的类可以通过直接复制类的所有位来序列化.对于不包含指针成员且既未进行版本控制也未进行跟踪的 POD 数据类型,尤其如此.一些档案,例如不可移植的二进制档案strong>可以让我们利用这些信息大大加快序列化速度.
为了表明按位序列化的可能性,使用了头文件 is_bitwise_serializable.hpp 中定义的类型特征:
To indicate the possibility of bitwise serialization the type trait defined in the header file is_bitwise_serializable.hpp is used:
这里是关键点:这个优化
Here are the key points: this optimization
- 在它适用的归档类型中是可选的
不适用于所有存档类型,例如
- is optional in the archive types where it does apply
doesn't apply to all archive types e.g.
无法通过复制原始内存表示来实现需要可移植的二进制存档(因为它依赖于实现和平台)
a binary archive that needs to be portable could not be implemented by copying out the raw memory representation (because it is implementation and platform depenedent)
文本存档可能不希望对此进行优化(例如,它有不同的目标,例如人类可读的 XML",他们可能不想对您的 vector;
作为一个大的 bas64 编码 blob).
a text archive might not desire to optimize this (e.g. it has different goals to, like "human readable XML", they might not want to encode your vector<A>
as a large bas64 encoded blob).
请注意,这也解释了 is_bit_wise_serializable<T>
并非部分专门用于具有 is_pod<T>::value == true
的任何类型(这在技术上可以很容易完成):
Note that this also explains that is_bit_wise_serializable<T>
is not partially specialized for any type that has is_pod<T>::value == true
(This could technically be done easily):
- 某些类可能对序列化它们的所有状态不感兴趣(因此,使用按位复制比仅选择有趣的位(双关语)要占用更多空间)
- some classes might not be interested in serializing all their state (so using bitwise copy would take a lot more space than just selecting the interesting bits (pun intended))
您没有特别问,但这是工作实现的样子:
You didn't ask, specifically, but this is what the working implementation would look like:
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <sstream>
struct A { int a; char b;
template <typename Ar> void serialize(Ar& ar, unsigned) {
ar & a;
ar & b;
}
};
BOOST_IS_BITWISE_SERIALIZABLE(A)
int main() {
std::ostringstream oss;
boost::archive::binary_oarchive oa(oss);
A data { 1, 'z' };
oa << data;
}
这篇关于提高序列化按位可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!