From 088caa68fb8efd8624709d643913b8a7e1218f8a Mon Sep 17 00:00:00 2001 From: Martin Leitner-Ankerl Date: Wed, 2 Aug 2023 19:54:11 +0200 Subject: [PATCH] refactor: use "if constexpr" in std::vector's Serialize() This gets rid of unnecessarily creating a temporary object T() to call the right function. --- src/serialize.h | 47 ++++++++++++++++------------------------------- 1 file changed, 16 insertions(+), 31 deletions(-) diff --git a/src/serialize.h b/src/serialize.h index 8dd14cd0e33..72672b459e4 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -649,9 +649,6 @@ template inline void Unserialize(St * vector * vectors of unsigned char are a special case and are intended to be serialized as a single opaque blob. */ -template void Serialize_impl(Stream& os, const std::vector& v, const unsigned char&); -template void Serialize_impl(Stream& os, const std::vector& v, const bool&); -template void Serialize_impl(Stream& os, const std::vector& v, const V&); template inline void Serialize(Stream& os, const std::vector& v); template void Unserialize_impl(Stream& is, std::vector& v, const unsigned char&); template void Unserialize_impl(Stream& is, std::vector& v, const V&); @@ -783,38 +780,26 @@ void Unserialize(Stream& is, prevector& v) /** * vector */ -template -void Serialize_impl(Stream& os, const std::vector& v, const unsigned char&) +template +void Serialize(Stream& os, const std::vector& v) { - WriteCompactSize(os, v.size()); - if (!v.empty()) - os.write(MakeByteSpan(v)); -} - -template -void Serialize_impl(Stream& os, const std::vector& v, const bool&) -{ - // A special case for std::vector, as dereferencing - // std::vector::const_iterator does not result in a const bool& - // due to std::vector's special casing for bool arguments. - WriteCompactSize(os, v.size()); - for (bool elem : v) { - ::Serialize(os, elem); + if constexpr (std::is_same_v) { + WriteCompactSize(os, v.size()); + if (!v.empty()) + os.write(MakeByteSpan(v)); + } else if constexpr (std::is_same_v) { + // A special case for std::vector, as dereferencing + // std::vector::const_iterator does not result in a const bool& + // due to std::vector's special casing for bool arguments. + WriteCompactSize(os, v.size()); + for (bool elem : v) { + ::Serialize(os, elem); + } + } else { + Serialize(os, Using>(v)); } } -template -void Serialize_impl(Stream& os, const std::vector& v, const V&) -{ - Serialize(os, Using>(v)); -} - -template -inline void Serialize(Stream& os, const std::vector& v) -{ - Serialize_impl(os, v, T()); -} - template void Unserialize_impl(Stream& is, std::vector& v, const unsigned char&)