21. Template Dispatch
In a hot-path market data router, we want compile-time dispatch to avoid virtual calls and branches. Template specialization can steer types to specific lanes with zero overhead if instantiation behavior is well understood.
template<class T> struct Buf { static constexpr int id = 0; };
template<> struct Buf<float> { static constexpr int id = 1; };
template<class T> int route() { return Buf<T>::id; }
int main() { return route<float>(); }
Part 1.
What does main return, and which templates/specializations are instantiated? Explain briefly how the specialization is selected.
Part 2.
(1) When and why use extern template and explicit instantiation here?
(2) Where must explicit specializations be defined to satisfy ODR?
(3) Why can't you partially specialize function templates; preferred alternative idioms?
(4) Compare if constexpr versus class-template specialization for routing.
(5) How does template bloat influence I-cache locality and branch predictor stability?
Answer
Answer (Part 1)
main returns 1. Instantiating route<float> uses Buf<float>; the explicit specialization Buf<float> is selected at compile time, so Buf<float>::id is 1.
Answer (Part 2)
(1) Use extern template to suppress implicit instantiation in many TUs, and explicitly instantiate in one TU to reduce code size and link time.
(2) Define specializations at the same namespace scope as the primary and make them visible before use in each TU to avoid unintended primary instantiation.
(3) C++ forbids partial specialization of function templates; use overloads with enable_if/concepts or delegate to class-template specializations.
(4) if constexpr keeps logic in one place and can prune branches; class-template specialization cleanly isolates policies and may improve cache locality.
(5) More instantiations enlarge text size, evicting hot code from I-cache and increasing fetch misses, harming latency predictability.