Template (C++)
This is used a lot. For example, STL.
Function templates allow us to operate with generic types, so that the function we implement can be adapted to more than one type or class without repeating the entire code for each type. This is the idea behind Template Method Design Pattern.
Resources
In C++ this can be achieved using template parameters. The format for declaring function templates with type parameters is:
Difference between keyword
class
and keywordtypename
?There is no difference. Its use is indistinct, since both expressions have exactly the same meaning and behave exactly the same way.
Class Template
Below is an incomplete implementation of a linkedList (full code in a2q1 of CS247):
- Notice that you only need to declare
template<typename T>
at the beginning of the class, and then you’re able to use the typeT
inside the class as much as you’d like - Also, notice that every time you use the class name, you need to use
List<T>
orMyIterator<ReturnType>
Warning
Template definition of methods must be written in the Header File, because the template needs to know the next field exists.
You should understand how templates are actually implemented at compiler level (more below).
Function Template
For example, to create a template function that returns the greater one of two objects we could use:
We can also define function templates that accept more than one type parameter, simply by specifying more template parameters between the angle brackets. For example:
For each use of
MyIterator<T>
, compiler generates another copy of the class withT
substituted where necessary. Afterwards, compiles as usual.No runtime
const
using templates, its as if we wrote our ownIterator
/ConstIterator
.
Class Template
I think this is the part that gets me the most confused. No, it’s just that you need to define these in the Header File. And just start with declaring template <typename T>
Resources:
- https://www.programiz.com/cpp-programming/class-templates
- https://www.codeproject.com/Articles/48575/How-to-Define-a-Template-Class-in-a-h-File-and-Imp
Variadic Template
A variadic template is a class or function template that supports an arbitrary number of argument.
- https://www.geeksforgeeks.org/variadic-function-templates-c/
- https://learn.microsoft.com/en-us/cpp/cpp/ellipses-and-variadic-templates?view=msvc-170
For example, when you use make_shared
and you pass in the constructor arguments,