Back to TILs

C++ templates — order

Date: 2023-01-01Last modified: 2024-11-02

Table of contents

C++ template can be trick.

template <typename T> void print1(T)   { fmt::print("Generic\n"); }
template <typename T> void print1(T *) { fmt::print("Overload\n"); }
template <>           void print1(double *) { fmt::print("Specialization\n"); }

// Same functions as above, but in diferent order.
template <typename T> void print2(T)   { fmt::print("Generic\n"); }
template <>           void print2(double *) { fmt::print("Specialization\n"); }
template <typename T> void print2(T *) { fmt::print("Overload\n"); }
  double d = 1.5;
  print1(&d);  // Specialization
  print2(&d);  // Overload

Possible output

Specialization
Overload