theor
theor

Reputation: 1595

How to implement a C++ serializer the idiomatic way?

As an exercise, I'm implementing an UBJson serializer in several languages. My question is: is there an idiomatic way to imlpement a custom format reader and writer in C++ ? For example, I thought of implementing another boost::serialization archive type.

More details : the type-introspection part is not a problem - if I ever use my implementation, it's to replace an already present json serializer. I also understand the notion of recursive serialization. The real question is : should I create readInt, writeString methods, or just make two templated read and write methods, or... ?

Upvotes: 1

Views: 379

Answers (1)

RandyGaul
RandyGaul

Reputation: 1915

Hmm I'm not aware of any idiomatic ways, though the standard strategy I am aware of is to only serializer the simplest of types. One could recursively break down a complex object into simpler pieces until the base POD types, such as int, char *, float are found. Then hand-made serialization routines for these base types are created.

Serialization of more complex types involves this recursive type introspection which results in a larger serialization routine built from smaller ones.

This sort of approach would however require some form of type introspection in C++, which turns out to be much more involved than the serialization itself. Here's an article I wrote on the topic: http://www.randygaul.net/2013/01/05/c-reflection-part-5-automated-serialization/

There are two main ways to write the actual serialization routines. The first way is to create a single serialization function that takes a bool for input/output.

void Serialize( type instance, bool input );

The second way is to write input and output as separate functions (which I myself prefer):

void Serialize( type instance );
Variant Deserialize( type info );

Templating the serialization routines, or just providing specific overloads is a matter of preference.

Upvotes: 1

Related Questions