Writing function templates
Generic code is key to avoid writing repetitive code. In C++, this is achieved with the help of templates. Classes, functions, and variables can be templated. Although templates are often seen as complex and cumbersome, they enable the creation of general-purpose libraries, such as the standard library, and help us write less and better code.
Templates are first-class citizens of the C++ language and could take an entire book to cover in detail. In fact, multiple recipes in this book deal with various aspects of templates. In this recipe, we will discuss the basics of writing function templates.
How to do it…
Do the following to create function templates:
- To create a function template, precede the function declaration with the
template
keyword followed by the list of template parameters in angle brackets:template <typename T> T minimum(T a, T b) { return a <= b ? a : b; } minimum(3, 4); minimum(3.99, 4...