3

Suppose I want to create a generic Serialize function that allows me to serialize built-in types, composed types and user-defined types. Then I see two ways to do it:

  • Overload based:

    • Serialize() is overloaded for all (supported) builtin-types
    • function template overloads are added for vector/map/tuple which delegate to the Serialize overloads for the element types
    • user-defined overloads are found with ADL
  • Class template specialization based:

    • one single Serialize function that delegates to SerializeHelper<T>()::serialize(...)
    • SerializeHelper is specialized for all built-in types
    • partial template specialization can be used to implement specialization for vector/map/tuple generically
    • users can provide specializations for their own types

What would be the pros and cons of each approach?

Also how do they compare concerning compile-time performance?

Note: despite the similar title, this question is not a duplicate of Template Specialization VS Function Overloading because that question is about ADL vs function template specialization (and not class template specialization).

StackedCrooked
  • 34,653
  • 44
  • 154
  • 278
  • 2
    @KyleKhalaf These are unrelated, we're not specializing functions – milleniumbug Jun 16 '17 at 22:18
  • Regarding "compile time performance" - anything involving templates is usually going to be slower (to compile). But why don't you just *try* and then benchmark it? – Jesper Juhl Jun 16 '17 at 22:23
  • 1
    even if it's not a dupe, it's clearly way too broad. I'm not going to vote to re-open a question that I'm going to immediately vote to close if it is re-opened. – xaxxon Jun 16 '17 at 22:52
  • 1
    One thing to consider: overloads allow implicit conversions. Template specializations do not. – aschepler Jun 16 '17 at 22:59
  • 1
    I have similar code for "serializing" objects to and from javascript. I do your second approach and have had major compilation performance issues to the point where I've written clang plugins so I can get information on template instantiations from the compiler. I now avoid using certain constructs (like maps and unique_ptr) in heavily templated areas due to compilation performance. Also, linking performance is significant, too. turning off deduplication in the mac linker and using ld.gold was required. Also linking is much faster with optimization turned on (but compilation is slower) – xaxxon Jun 16 '17 at 23:05
  • @aschepler Thanks! I didn't think of that. (Learning these insights is the reason why I started the question. I don't understand why it was closed.) – StackedCrooked Jun 17 '17 at 00:38
  • 1
    I've read that C++ compilers typically spend about 30% of their time resolving stream insertion/extraction overloads. – Malcolm McLean Jun 17 '17 at 00:42

0 Answers0