January 2019
Intermediate to advanced
512 pages
14h 5m
English
Function templates are generic functions—unlike the regular functions, a template function does not declare its argument types. Instead, the types are template parameters:
template <typename T> T increment(T x) { return x + 1; }
This template function can be used to increment a value of any type by one, for which adding one is a valid operation:
increment(5); // T is int, returns 6increment(4.2); // T is double, return 5.2char c[10];increment(c); // T is char*, returns &c[1]
Most template functions have some limitations on the types that are used as their template parameters. For example, our increment() function requires that the expression x + 1 is valid for the type of x. Otherwise, the attempt to instantiate the template ...