【问题标题】:Serialization member by member逐个成员序列化
【发布时间】:2015-04-14 13:36:40
【问题描述】:

我已经实现了一个template<typename T> Serializer,它适用于T 类型的任何普通可复制 对象,只是序列化sizeof(T) 字节。

然后我针对其他类型的兴趣实现了几个(部分)专业化,例如std::vector<T>std::bacis_string<T>。对于其他类型,我触发static_assert(is_trivially_copyable<T>::type, "Unsupported type");

这不是我想要的,因为我想避免序列化,例如带有裸指针的类型,例如:

struct C_style_vector{
    size_t size;
    int* ptr;
};

对于这种类型,我假设用户将定义一个临时专业化。相反,就目前而言,我的 Serializer 不适用于这样的类型:

struct Simple_type{
    double d;
    std::vector<int> v;
};

即使Simple_type 的每个成员都可以被我的班级序列化。

那么,我如何用裸指针捕获类型? 以及如何告诉我的序列化程序序列化仅由可序列化成员组成的类型,逐个成员序列化它

【问题讨论】:

  • 如果您曾经想知道为什么boost::serialization 箭头后面有如此庞大的木头,请不要再想了。

标签: c++ templates serialization template-specialization


【解决方案1】:

这实际上并不简单,并且不能在 C++ 中完成,如果没有一些用户添加,因为 C++ 中没有反射。

您可以使用 boost::fusion 之类的东西,但在这种情况下用户应该使用融合序列。我认为最好的方法是使用 boost::serialization,用户必须为自己的类型提供 serialize/deserialize 函数。

融合示例。

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");
};

Live example

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 2013-04-08
    • 1970-01-01
    • 2020-09-04
    • 2023-03-14
    • 2015-07-20
    • 2014-06-07
    • 2010-12-06
    • 2010-10-22
    相关资源
    最近更新 更多