C++ Templates
We have seen that functions can take arguments of specific types and have a
specific return type.
We consider templates, which allow us to work with generic types.
#include <iostream>
int add(const int x, const int y) {
return x + y;
}
int add(const double x, const double y) {
return x + y;
}
|
Using templates,
rather than repeating function code for each new type we wish to support,
we create a 'generic' function that performs the same operation
independent of the types of its parameters.
#include <iostream>
template <typename T>
T add(const T a, const T b) {
return a + b;
}
|
The Standard Template Library (STL)
Part of the C++ Standard Library, the Standard Template Library (STL)
contains many useful container classes and algorithms. As you might imagine,
these various parts of the library are written using templates and so are
generic in type. The containers found in the STL are lists, maps, queues,
sets, stacks, and vectors. The algorithms include sequence operations,
sorts, searches, merges, heap operations, and min/max operations.
The STL has many, many more containers and algorithms that you can use.
Great reference material:
- http://www.cplusplus.com/reference/stl and
- http://www.cplusplus.com/reference/algorithm/.
CITS2002 Systems Programming, Lecture 23, p14, 17th October 2023.
|