C++ ClassesLesson 40Free preview
C++ Templates
This lesson is part of C++ · All levels
Summary
Templates allow us to write a single piece of generic code that works for many types of data. C++ has a template for versatile functions such as max or swap, as well as a class template for containers such as Box or our version pairs. The compiler will produce a specific version of the type required (template instantiation), so it is efficient and remains type-safe.
Key points
- The Function template is written as a template <typename T> or template <class T> before the function definition.
- The class template is written as the template <typename T> class Name {...}; and used as the Name<int>.
- The type can be determined automatically from the argument or explicitly enforced as a maximum.
- Templates help avoid duplication of code for different data types.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.