C++ 逐成员序列化
我实现了一个C++ 逐成员序列化,c++,templates,serialization,template-specialization,C++,Templates,Serialization,Template Specialization,我实现了一个模板序列化程序,它可以处理任何类型为T的可复制对象,只需序列化sizeof(T)字节 然后我为其他感兴趣的类型实现了一些(部分)专门化,比如std::vector和std::bacis\u string。对于其他类型,我会触发一个静态断言(是可复制的::type,“不支持的类型”) 这不是我想要的,因为我想避免序列化,例如,带有裸指针的类型,例如: struct C_style_vector{ size_t size; int* ptr; }; 对于这类类型,我假设
模板序列化程序
,它可以处理任何类型为T
的可复制对象,只需序列化sizeof(T)
字节
然后我为其他感兴趣的类型实现了一些(部分)专门化,比如std::vector
和std::bacis\u string
。对于其他类型,我会触发一个静态断言(是可复制的::type,“不支持的类型”)代码>
这不是我想要的,因为我想避免序列化,例如,带有裸指针的类型,例如:
struct C_style_vector{
size_t size;
int* ptr;
};
对于这类类型,我假设用户将定义一个特殊的专门化。相反,到目前为止,我的序列化程序
无法处理以下类型:
struct Simple_type{
double d;
std::vector<int> v;
};
struct Simple\u类型{
双d;
std::向量v;
};
即使Simple_type
的每个成员都可以被我的类序列化
那么,如何用裸指针捕捉类型呢?
如何告诉我的序列化程序序列化仅由序列化成员组成的类型,按成员序列化成员?< p>它实际上并不简单,不能在C++中完成,因为没有C++用户的添加,因为在C++中没有反射。
您可以使用类似boost::fusion的东西,但在这种情况下,用户应该使用fusion序列。最好的方法是使用boost::serialization,我认为,用户必须为自己的类型提供序列化/反序列化
函数
融合的例子
template<bool Value, typename Next, typename Last>
struct is_serializable_impl
{
private:
static const bool cvalue = !boost::is_pointer<
typename boost::remove_reference<
typename boost::fusion::result_of::deref<Next>::type>::type>::value;
public:
static const bool value = Value && is_serializable_impl<
cvalue, typename boost::fusion::result_of::next<Next>::type, Last>::value;
};
template<bool Value, typename Last>
struct is_serializable_impl<Value, Last, Last>
{
static const bool value = Value;
};
template<typename T>
struct is_serializable :
is_serializable_impl<true, typename boost::fusion::result_of::begin<T>::type,
typename boost::fusion::result_of::end<T>::type>
{
};
template<typename T, typename = void>
struct serializer;
template<typename T>
struct serializer<T,
typename boost::enable_if<typename
boost::fusion::traits::is_sequence<T>::type>::type>
{
static_assert(is_serializable<T>::value, "Not serializable");
};
模板
结构是可序列化的
{
私人:
静态常量bool cvalue=!boost::是指针<
typename boost::删除\u引用<
typename boost::fusion::result_of::deref::type>::type>::value;
公众:
static const bool value=value&&is_serializable_impl<
cvalue,typename boost::fusion::result_of::next::type,Last>::value;
};
模板
结构是可序列化的
{
静态常量布尔值=值;
};
模板
结构是可序列化的:
是可序列化的吗
{
};
模板
结构序列化程序;
模板
结构序列化程序
{
静态断言(是可序列化::值,“不可序列化”);
};
如果你曾经想知道为什么箭后有这么多的木头,那就不要再想了。