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. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access