Template Specialization

Template specializations are a mechanism to tell the compiler : if i pass you this type, don't do the default behavior of replacing the argument type. Instead, use the implementation that i am going to give you.


#include <cstring>

template <typename T> T maximum(T a, T b);

template <> const char *maximum<const char *>(const char *a, const char *b);

int main(int argc, char *argv[]) {
  double a{23.5};
  double b{51.2};

Idouble max1 = maximum(a, b);

  const char *c{"wild"};
  const char *d{"animal"};

  const char *max2 = maximum(c, d);

  return 0;
}

template <typename T> T maximum(T a, T b) { return (a > b) ? a : b; }

template <> const char *maximum<const char *>(const char *a, const char *b) {
  return (std::strcmp(a, b) > 0) ? a : b;
}