© Will Briggs 2021
W. BriggsC++20 for Lazy Programmershttps://doi.org/10.1007/978-1-4842-6306-8_20

20. Templates

Will Briggs1  
(1)
Lynchburg, VA, USA
 

Would I write a function or class that takes ints and another just like it except it takes strings and another except it takes doubles? That doesn’t sound lazy! This chapter enables us to write it once, using templates.

Function templates

Recall this function for swapping ints, renamed here for convenience, from Chapter 8:
void mySwap (int& arg1, int& arg2)
{
    int temp = arg2; arg2 = arg1; arg1 = temp;
}
That’s fine for int, but what if I want doubles? Heffalumps? Or a mix? Here’s the fix so I can swap int with int, int with double, heffalumps with snarks, anything, as long as C++ knows how to use =

Get C++20 for Lazy Programmers: Quick, Easy, and Fun C++ for Beginners 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.