Skip to main content

12. Template Functions & classes

14/03/23

Do not use a macro where the evaluation of the parameters may have a side-effect. max(a++,b++) -> Evaluating these parameters alters a value

Template Functions

  • Can use function overloading to have multiple versions of the same function
  • Specify how to create functions of a certain format, if they are ever needed, e.g.:
template <typename T>
T mymax(T a, T b){
return a > b ? a : b;
}
  • Type placeholders are used, and are replaced implicitly.

What they actually do

  • The compiler will actually generate the functions which are needed, according to the parameters
  • If there are any problems, it will not compile
  • this is NOT something done at runtime

How to create template functions

  • Easy way to create these functions:
    • First manually generate a function for specific types
    • Next replace all copies of the types by an identifier
    • Then add the keyword template at the beginning and put the type(s) in the <> with keyword typename (or class)

Template classes

  • Can make template forms of entire classes as well as individual functions
  • Much easier if the methods are defined inline within the class declaration

Alter external member function definitions

  • Add prior to each member function definition template <typename T>
  • Add the <T> to the end of the class name in any external member function implementation/definition
  • Find each occurrence of the templated type and replace it by the templated type name