C++ – When one should use template specialization, if not for metaprogramming

ctemplates

When do we use template specializations for in C++, if not for SFINAE or metaprogramming? type_traits, enable_if and others rely on it a lot, but I'm more curious about situations which are more "obvious" uses of templates – type-agnostic algorithms and objects.

One can easily create an artificial example of algorithm which does completely different things for different types, so I'd like to limit the scope to more "real-life" scenarios. Specifically, the following properties should be satisfied:

  1. One can formulate an invariant of a generic version of template (so it makes sense to talk about specialization), and
  2. Specialized version do not violate any invariants of the generic version (if it does, it's probably a bad specialization and a separate class/function should be created instead).

I have three examples in my mind:

  • std::vector<bool>. It's known to have different interface from generic vector (1, 2) and therefore I consider it a bad example – it does not satisfy property 2.
  • std::hash. Despite it does not have "generic" implementation, it has "generic" invariant.
  • std::swap. It satisfies both properties.

These examples, though, look very specific to me. I'm wondering if it's possible to describe when one should use template specialization. E.g. "if you have a type-agnostic container which has a strictly better implementation for some specific type" is probably true, but, again, rather specific.

Best Answer

When one should use template specialization, if not for metaprogramming?

The "classical" thing, and even the one you mention at the end, is to refine a given generic implementation for a specific (set of) types.

Prime example here would be container or algorithm "optimizations" for trivial types. (See e.g. std::copy)

There's nothing meta about this as far as I can tell: For some types, a given specialized version will be objectively better, keeping all requirements of the generic version, so it will be implemented as soon as needed.

Related Topic