Skip to Content
C++ for Lazy Programmers: Quick, Easy, and Fun C++ for Beginners
book

C++ for Lazy Programmers: Quick, Easy, and Fun C++ for Beginners

by Will Briggs
October 2019
Beginner
655 pages
12h 5m
English
Apress
Content preview from C++ for Lazy Programmers: Quick, Easy, and Fun C++ for Beginners
© Will Briggs 2019
W. BriggsC++ for Lazy Programmershttps://doi.org/10.1007/978-1-4842-5187-4_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 just like it except it takes Ubergeeks? That doesn’t sound lazy! This chapter enables us to write it once, using templates.

Function templates

Recall this function for swapping ints, from Chapter 8:
void swap (int& arg1, int& arg2)
{
      int temp = arg2; arg2 = arg1; arg1 = temp;
}
That’s fine for int, but what if I want doubles? strings? Heffalumps? I don’t want to write new versions for every type I encounter! Here’s the fix.
template <typename T>
void swap (T& arg1, T& arg2)
{
      T temp = arg2; ...
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.
Start your free trial

You might also like

C++20 for Lazy Programmers: Quick, Easy, and Fun C++ for Beginners

C++20 for Lazy Programmers: Quick, Easy, and Fun C++ for Beginners

Will Briggs

Publisher Resources

ISBN: 9781484251874Purchase LinkPublisher Website