Understanding template functions and classes
Templates provide the ability to create generic functions and classes by abstracting the data types associated with those functions and classes. Template functions and classes can both be carefully written in such a way as to genericize the relevant data types that underlie these functions and classes.
Let’s begin by examining how to create and utilize template functions.
Creating and using template functions
Template functions parameterize the types of arguments in a function in addition to the arguments themselves. Template functions require the body of the function to be applicable to almost any data type. Template functions can be member or non-member functions. Operator overloading can help ensure that the bodies of template functions are applicable to user defined types – we’ll see more of that shortly.
The keyword template
, along with angle brackets, <
>
, and placeholders for the type names...