Legacy C++ › 4. Templates and Namespaces
Function Templates
Generic functions, template argument deduction and overloading.
Explanation
A function template is a recipe for generating functions for different types:
template <typename T>
T maxOf(const T& a, const T& b) { return (a < b) ? b : a; }
The compiler deduces T from the arguments (maxOf(3, 7) → T = int) and instantiates a real function. You may also specify it explicitly: maxOf<double>(3, 7.5). A template compiles only if the operations used (< here) exist for the chosen type; this is “duck typing” checked at instantiation.
Template definitions normally live in headers, because the compiler needs the full definition to instantiate them. A plain function overload is preferred over a template when both match equally well.
Example
#include <iostream>
#include <string>
template <typename T>
const T& maxOf(const T& a, const T& b) { return (a < b) ? b : a; }
template <typename T>
void swapValues(T& a, T& b) { T tmp = a; a = b; b = tmp; }
template <typename T, typename U>
void show(const T& a, const U& b) { std::cout << a << " & " << b << "\n"; }
// non-template overload wins for const char* (so we compare text, not addresses)
const char* maxOf(const char* a, const char* b) {
return std::string(a) < std::string(b) ? b : a;
}
int main() {
std::cout << maxOf(3, 7) << " " << maxOf(2.5, 1.5) << "\n";
std::cout << maxOf<double>(3, 7.5) << "\n"; // explicit argument
std::cout << maxOf(std::string("pear"), std::string("apple")) << "\n";
std::cout << maxOf("pear", "apple") << "\n"; // overload
int a = 1, b = 2;
swapValues(a, b);
show(a, "text");
return 0;
}
Common pitfalls
- Deduction conflicts:
maxOf(3, 7.5)fails (intvsdouble). Cast, or specify<double>. - Errors appear at instantiation, are long and cryptic. Read the first error and the “required from here” line.
- Template code in
.cppfiles causes linker errors; put definitions in the header. - Returning a reference to a temporary (
maxOf(a, b + 1)) dangles. - In C++03 you must write
> >(with a space) for nested templates:vector<vector<int> >.
Legacy vs modern
C++11 adds >> handling, variadic templates and auto; C++14 allows auto parameters in lambdas; C++20 concepts let you state requirements (template <std::totally_ordered T>) and give readable errors. See Concepts.
Exercises
1. Write a template T clamp(T v, T lo, T hi).
template <typename T>
T clamp(T v, T lo, T hi) { return v < lo ? lo : (hi < v ? hi : v); }