Generic Programming - Simple C++ Templates
C++
C++ is a strongly typed language - all variables must have a specific type, either explicitly defined by the programmer or inferred during compilation. However, function operations are often identical regardless of the data type being operated on.
For example, the body of a function that sums two numbers will be identical for both int
and float
types.
C++ allows generic functions to be created using templates. This means that the function can work on many different data types without being rewritten for each one. The template generates an ordinary type or function when it is compiled, based on the arguments supplied to the template.
Simple Template
Simple template definition where all input parameters and return variables are of the same type:
Template with Different Data Types Input
Templates can accept different data types - with the return data type specified in the template definition:
This definition allows different variable types as input parameters, and specifies that the return type will be the same as the type of the first supplied parameter (in this case, T
).
Specify Values - Non-type Parameters
You can also specify values as part of the template specification:
template <typename T, int N>
class Array
{
private:
T m_Array[N];
int m_size = 0;
public:
}
In this case, the class has a member m_Array
which is initialised with N
elements of type T
.
The template is invoked like this:
// The object will have a member m_Array, an array of ints with size 10.
Array intArray<int, 10>
References
comments powered by Disqus