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 ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.