16.1.1. Function Templates
Rather than defining a new function for each type, we can define a function template. A function template is a formula from which we can generate type-specific versions of that function. The template version of compare
looks like
template <typename T>int compare(const T &v1, const T &v2){ if (v1 < v2) return -1; if (v2 < v1) return 1; return 0;}
A template definition starts with the keyword template
followed by a template parameter list, which is a comma-separated list of one or more template parameters bracketed by the less-than (<
) and greater-than (>
) tokens.
Note
In a template definition, the template ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.