Skip to content

Commit ca62563

Browse files
committed
Add a generic approach for (de)serialization of objects using code in other classes
This adds the (internal) Wrapper class, and the Using function that uses it. Given a class F that implements Ser(stream, const object&) and Unser(stream, object&) functions, this permits writing e.g. READWRITE(Using<F>(object)).
1 parent e8e7995 commit ca62563

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/serialize.h

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -442,6 +442,32 @@ I ReadVarInt(Stream& is)
442442
}
443443
}
444444

445+
/** Simple wrapper class to serialize objects using a formatter; used by Using(). */
446+
template<typename Formatter, typename T>
447+
class Wrapper
448+
{
449+
static_assert(std::is_lvalue_reference<T>::value, "Wrapper needs an lvalue reference type T");
450+
protected:
451+
T m_object;
452+
public:
453+
explicit Wrapper(T obj) : m_object(obj) {}
454+
template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
455+
template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
456+
};
457+
458+
/** Cause serialization/deserialization of an object to be done using a specified formatter class.
459+
*
460+
* To use this, you need a class Formatter that has public functions Ser(stream, const object&) for
461+
* serialization, and Unser(stream, object&) for deserialization. Serialization routines (inside
462+
* READWRITE, or directly with << and >> operators), can then use Using<Formatter>(object).
463+
*
464+
* This works by constructing a Wrapper<Formatter, T>-wrapped version of object, where T is
465+
* const during serialization, and non-const during deserialization, which maintains const
466+
* correctness.
467+
*/
468+
template<typename Formatter, typename T>
469+
static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
470+
445471
#define VARINT(obj, ...) WrapVarInt<__VA_ARGS__>(REF(obj))
446472
#define COMPACTSIZE(obj) CCompactSize(REF(obj))
447473
#define LIMITED_STRING(obj,n) LimitedString< n >(REF(obj))

0 commit comments

Comments
 (0)