C/C++ Arena

Step 7 of 8

Template specialization

Sometimes one type needs different behavior from the general template. A full specialization provides a replacement for exactly that type:

template <typename T>
struct TypeName { static std::string get() { return "unknown"; } };

template <>
struct TypeName<int> { static std::string get() { return "int"; } };

template <> with empty brackets means "all the parameters are already fixed". The compiler picks the most specific match. This is how the standard library implements things like std::hash<std::string>, and how you add support for your own types to library templates.

Your turn: add specializations of TypeName for double ("double"), bool ("bool") and std::string ("string").

Previous: Values as template parameters Next: Challenge: a MinStack<T>