Abstract
You may have noticed that some of the overloaded functions in Ex8_15 consisted of exactly the same code. The only difference were the types that appear in the parameter list. It seems an unnecessary overhead to have to write the same code over and over, just because it has to work for different types. And indeed it is. In such situations you can write the code just once, as a function template. The Standard Library, for instance, makes heavy use of this feature to ensure that its functions work optimally with any type, including your own custom types, which of course the library cannot know about in advance. This chapter introduces the basics of defining your own function templates that work with any type you desire.
Access this chapter
Tax calculation will be finalised at checkout
Purchases are for personal use only
Notes
- 1.
constexpr and consteval functions can also be used in non-type template argument expressions. These are functions that, respectively, can or can only be evaluated at compile time. You do not often need these, though, so we do not discuss constexpr or consteval functions any further in the book.
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). Function Templates. In: Beginning C++20. Apress, Berkeley, CA. https://doi.org/10.1007/978-1-4842-5884-2_10
Download citation
DOI: https://doi.org/10.1007/978-1-4842-5884-2_10
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)