Chapter 26. Tempting C++ Templates

In This Chapter

  • Examining how templates can be applied to functions

  • Combining common functions into a single template definition

  • Defining a template or class

  • Reviewing the advantages of a template over the more generic "void" approach

The standard C++ library provides a complete set of math, time, input/output, and DOS operations, to name just a few. Many of the earlier programs in this book use the so-called character string functions defined in the include file strings. The argument types for many of these functions are fixed. For example, both arguments to strcpy(char*, char*) must be a pointer to a null-terminated character string — nothing else makes sense.

There are functions that are applicable to multiple types. Consider the example of the lowly maximum() function, which returns the maximum of two arguments. All of the following variations make sense:

int maximum(int n1, int n2); // return max of two integers
unsigned maximum (unsigned u1, unsigned u2);
double   maximum (double d1, double d2);
char     maximum (char c1, char c2);

I would like to implement maximum() for all four cases.

Of course, I could overload maximum() with all the possible versions:

double maximum(double d1, double d2)
{
    if (d1 > d2)
    {
        return d1;
    }
    return d2;
}
int maximum(int n1, int n2)
{
    if (n1 > n2)
    {
        return n1;
    }
    return n2;
}
char maximum(char c1, char c2)
{
    if (c1 > c2)
    {
        return c1;
    }
    return c2;
}

// ...repeat for all other numeric types...

This approach works. Now C++ selects ...

Get C++ For Dummies®, 6th 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.