Defining templates

Returning back to the two versions of the maximum function, the routine is the same for both; all that has changed is the type. If you had a generic type, let's call it T, where T could be any type that implements an operator>, the routine could be described by this pseudocode:

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

This will not compile because we have not defined the type T. Templates allow you to tell the compiler that the code uses a type and will be determined from the parameter passed to the function. The following code will compile:

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

The template declaration specifies the type that will be used using the ...

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.