From ca33451535dc29f64d37c49af8b22142d7716d0d Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Fri, 7 Jul 2017 15:48:13 -0700 Subject: [PATCH] Introduce new serialization macros without casts 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. --- src/serialize.h | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/serialize.h b/src/serialize.h index c84a1567f16d4..c9e994f84406e 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -199,6 +199,30 @@ template 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 \ + void Serialize(Stream& s) const \ + { \ + static_assert(std::is_same::value, "Serialize type mismatch"); \ + SerializationOps(*this, s, CSerActionSerialize()); \ + } \ + template \ + void Unserialize(Stream& s) \ + { \ + static_assert(std::is_same::value, "Unserialize type mismatch"); \ + SerializationOps(*this, s, CSerActionUnserialize()); \ + } \ + template \ + static inline void SerializationOps(Type& obj, Stream& s, Operation ser_action) \ + + #ifndef CHAR_EQUALS_INT8 template inline void Serialize(Stream& s, char a ) { ser_writedata8(s, a); } // TODO Get rid of bare char #endif