Skip to main content

Function Templates

  • Chapter
  • First Online:
Beginning C++20
  • 3123 Accesses

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.

This is a preview of subscription content, log in via an institution to check access.

Access this chapter

Chapter
USD 29.95
Price excludes VAT (USA)
  • Available as PDF
  • Read on any device
  • Instant download
  • Own it forever
eBook
USD 54.99
Price excludes VAT (USA)
  • Available as EPUB and PDF
  • Read on any device
  • Instant download
  • Own it forever

Tax calculation will be finalised at checkout

Purchases are for personal use only

Institutional subscriptions

Notes

  1. 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

Authors

Rights and permissions

Reprints and permissions

Copyright information

© 2020 Ivor Horton and Peter Van Weert

About this chapter

Check for updates. Verify currency and authenticity via CrossMark

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

Publish with us

Policies and ethics