Specialized templates

In some cases, you may have a routine that works for most types (and a candidate for a templated function), but you may identify that some types need a different routine. To handle this, you can write a specialized template function, that is, a function that will be used for a specific type and the compiler will use this code when a caller uses types that fit this specialization. As an example, here is a fairly pointless function; it returns the size of a type:

    template <typename T> int number_of_bytes(T t) 
{
return sizeof(T);
}

This works for most built-in types, but if you call it with a pointer, you will get the size of the pointer, not what the pointer points to. So, number_of_bytes("x") will return 4 (on a 32-bit system) rather than 2 for the size of the char array. You may decide that you want a specialization for char* pointers that uses the C function, strlen, to count the number of characters in the string until the NUL character. To do this, you need a similar prototype to the templated function, replacing the template parameter with the actual type, and since the template parameter is not needed you miss this out. Since this function is for a specific type, you need to add the specialized type to the function name:

    template<> int number_of_bytes<const char *>(const char *str) 
{
return strlen(str) + 1;
}

Now when you call number_of_bytes("x") the specialization will be called and it will return a value of 2.

Earlier, we defined a templated function to return a maximum of two parameters of the same type:

    template<typename T> 
T maximum(T lhs, T rhs)
{
return (lhs > rhs) ? lhs : rhs;
}

Using specialization, you can write versions for types that are not compared using the > operator. Since it makes no sense to find the maximum of two Booleans, you can delete the specialization for bool:

    template<> bool maximum<bool>(bool lhs, bool rhs) = delete;

This now means that, if the code calls maximum with bool parameters, the compiler will generate an error.