Electively serialize to/from XML or binary in C++

The lexical_cast template

We’ll do a little excursion away from serialization to another part of my core library. Basically, lexical_cast is meant as a template to solve the ever recurring problem of typecasting from numeric types to strings and vice versa.

This is the basic implementation. As you see, it makes use of the stringstream‘s wide range of streaming operands for conversion.

I also added some specializations which string streams could not handle, e.g. converting a bool to a string should result in “true” or “false”.

This gets more interesting when we look at the enumerations I mentioned before. For example, I have an enum which defines the nature of an Entity.

Have a look back at the serialization code I presented to you. In line 13, the type of the Entity is written using writeParameter and the enum (which is casted to s32 by the compiler implicitly) as the second parameter (value) and the lexical_cast of the enum to string as the third parameter (readable). Since there is no specialization of the template available for EEntityType yet, this would lead to a conversion from the numeric value to its string representation, e.g. ET_ROOT becomes “0″.

I would prefer to have a “root” then, and other nice descriptive strings for the other possible values, and that’s what the following lexical_cast specialization does:

That way, a nice speaking value is available for the enum and the XML serializer will gratefully prefer this one over the numeric value. The binary serializer instead doesn’t care and writes the s32 as binary.

The other way round is a bit more complicated. Since s32 could match for any enum we have, the deserializer will either fill the s32 or the string parameter which are passed by reference to the readParameter method. It’s then upon you to deal with the result.

I’ll leave it to you implement the required template<> inline const vte::world::EEntityType lexical_cast( const std::string& type ) method.

If you like this article, please share a slice of your pie and click here:

Pages:

1 2 3 4 5 6 7 8 9


Write a Comment

Take a moment to comment and tell me what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!