I want to generate serialization/deserialization code for
class Object
{
string a;
int b;
long c;
char d;
};
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?
code should look like
void SerializeObject(ostream os)
{
serialize(object.a, os);
serialize(object.b, os);
//serialize(object.member, os);
}
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?
my aim is:
User defines mpl::vector<String, int, long, char> for above object and my metaprogram can generate the coded needed.
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)
)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With