16.1.1. Function Templates

Image

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.