本文介绍了Boost MPL生成对象序列化的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为

class Object
{
    string a;
    int b;
    long c;
    char d;
};

通过查看mpl序列,但我需要能够识别对象,好吧,我不知道如何得到它的成员的名字,我必须知道吗?

by looking at a mpl sequence, but I need to be able to identify object and retrieve it back as well, I can't figure out how would I get the names of it members, do I have to know it?

代码应该看像

void SerializeObject(ostream os)
{
   serialize(object.a, os);
   serialize(object.b, os);

   //serialize(object.member, os);
}



我想通过用户定义一个mpl序列

I want to generate above code by user only defining a mpl sequence corresponding the object layout, is it doable, can you give me some hints?

我的目标是:

用户定义

推荐答案

考虑一个 boost :: fusion code> BOOST_FUSION_ADAPT_STRUCT()以将您的结构推广到融合序列(随机访问),例如一旦你定义了上述结构,你可以做一些

Consider a boost::fusion, and use the macro BOOST_FUSION_ADAPT_STRUCT() to promote your structure to a fusion sequence (random access), e.g. once you've defined the above structure, you can do something like

BOOST_FUSION_ADAPT_STRUCT(
    Object,
    (std::string, a)
    (int, b)
    (long, c)
    (char, d)
)

现在它已经被提升,你可以简单地使用 for_each 例如:

Now that it's been promoted, you can simply use a for_each to iterate over the members, something like:

template<typename archive>
struct serializer {
   serializer(archive& ar):ar(ar) {}

   template<typename T>
   void operator()(const T& o) const {
      ar & o;  // assuming binary for example...
   }
   archive& ar;
};

template<typename archive, typename sequence>
void serialize(archive& ar, sequence const& v) {
   boost::fusion::for_each(v, serializer<archive>(ar));
}

要使用,它应该很简单:

To use, it should be as simple as:

Object foo; // instance to serialize
serialize(<archive>, foo);

这篇关于Boost MPL生成对象序列化的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:37