42 Common Core CPP Module 07
- Templates
Templates allow you to define the behaviour of a class or function for different data types. A template is a construct that lets the compiler generate a regular class or function at compile time, based on the type argments provided by the user.
Example:
template <typename T>
T minimum(const T& lhs, const T& rhs)
{
return lhs < rhs ? lsh : rhs;
}
This code defines a template for a functiion that returns a value of type T and takes two parameters of type T.
- By convention, template parameters are written as single uppercase letters (like
T) - The keyword
typenameindicates that the parameter is a placeholder for a type - When the function is called, the compiler replaces every instance of
Twith the actual type specified or deduced - The process by which the compiler generates a concrete class or function from a template is called template instantiation. For example,
minimun<int>is an instantitation of the templateminimum<T>.
- By convention, the implementations of member functions for templates classes are placed in a separate
.tppfile. - Each member function must be preceded by
template <typename T>to declare that it belongs to a template. - When defining methods outside the class, you must write
Class<T>::functioninstead ofClass::function, to specify that the function beloong to the template classClass<T>.
Example:
//MyClass.hpp
template <typename T>
class MyClass
{
void print(const T& val);
};
#include "MyClass.tpp"
//MyClass.tpp
template <typename T>
void MyClass<T>::print(const T& val)
{
std::cout << val << std::endl;
}