Skip to content

Commit

Permalink
Introduce new serialization macros without casts
Browse files Browse the repository at this point in the history
This new approach uses a static method which takes the object as
a argument. This has the advantage that its constness can be a
template parameter, allowing a single implementation that sees the
object as const for serialization and non-const for deserialization,
without casts.

More boilerplate is included in the new macro as well.
  • Loading branch information
sipa authored and furszy committed Jul 3, 2021
1 parent ace7d14 commit 6bb135e
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/serialize.h
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,28 @@ template<typename X> const X& ReadWriteAsHelper(const X& x) { return x; }
SerializationOp(s, CSerActionUnserialize()); \
}

/**
* Implement the Serialize and Unserialize methods by delegating to a single templated
* static method that takes the to-be-(de)serialized object as a parameter. This approach
* has the advantage that the constness of the object becomes a template parameter, and
* thus allows a single implementation that sees the object as const for serializing
* and non-const for deserializing, without casts.
*/
#define SERIALIZE_METHODS(cls, obj) \
template<typename Stream> \
void Serialize(Stream& s) const \
{ \
static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \
SerializationOps(*this, s, CSerActionSerialize()); \
} \
template<typename Stream> \
void Unserialize(Stream& s) \
{ \
static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \
SerializationOps(*this, s, CSerActionUnserialize()); \
} \
template<typename Stream, typename Type, typename Operation> \
static inline void SerializationOps(Type& obj, Stream& s, Operation ser_action) \

/*
* Basic Types
Expand Down

0 comments on commit 6bb135e

Please sign in to comment.