16.1. Defining a Template

Imagine that we want to write a function to compare two values and indicate whether the first is less than, equal to, or greater than the second. In practice, we’d want to define several such functions, each of which will compare values of a given type. Our first attempt might be to define several overloaded functions:

// returns 0 if the values are equal, -1 if v1 is smaller, 1 if v2 is smallerint compare(const string &v1, const string &v2){    if (v1 < v2) return -1;    if (v2 < v1) return 1;    return 0;}int compare(const double &v1, const double &v2){    if (v1 < v2) return -1;    if (v2 < v1) return 1;    return 0;}

These functions are nearly identical: The only difference between them is the type of their parameters. ...

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.