Abstract
Both function and class templates are used extensively throughout the C++ Standard Library to provide powerful generic utilities, algorithms, and data structures. You learned about templates that the compiler uses to create functions in Chapter 10; this chapter is about templates that the compiler uses to create classes. Class templates are a powerful mechanism for generating new class types.
Access this chapter
Tax calculation will be finalised at checkout
Purchases are for personal use only
Notes
- 1.
- 2.
The actual swap<>() template is different in two aspects. First, it moves the objects if possible using move semantics. You’ll learn all about move semantics in the next chapter. Second, it is only conditionally noexcept. Concretely, it is noexcept only if its arguments can be moved without exceptions. Conditional noexcept specifications are a more advanced language feature we do not cover in this book.
- 3.
 The reason we cannot use the std::swap() from within our copy assignment operator is that std::swap() in turn would use the copy assignment operator. In other words, calling std::swap() here would result in infinite recursion!
- 4.
 Which in a way is fortunate, because the same developer that carelessly passed an invalid index to array[i-1] also mistakenly wrote an otherwise indefinite for loop. Do you see why?
- 5.
 As of C++20, you can in principle use certain class types (a specific subset of so-called literal classes, to be exact), but the restrictions on these class types are so severe we won’t discuss this possibility.
- 6.
 Detailing the precise built-in template argument deduction rules or explaining how to override or augment them with so-called user-defined deduction guides would lead us too far for this basic introduction. The good news though is that the built-in rules mostly work just fine!
Author information
Authors and Affiliations
Rights and permissions
Copyright information
© 2020 Ivor Horton and Peter Van Weert
About this chapter
Cite this chapter
Horton, I., Van Weert, P. (2020). Class Templates. In: Beginning C++20. Apress, Berkeley, CA. https://doi.org/10.1007/978-1-4842-5884-2_17
Download citation
DOI: https://doi.org/10.1007/978-1-4842-5884-2_17
Published:
Publisher Name: Apress, Berkeley, CA
Print ISBN: 978-1-4842-5883-5
Online ISBN: 978-1-4842-5884-2
eBook Packages: Professional and Applied ComputingApress Access BooksProfessional and Applied Computing (R0)