A function template represents a family of functions. Accordingly, a class template represents a family of classes. Today, I want to introduce class templates.
Defining a class template is straightforward.
Definition of a Class Template
Assume you have a class A
rray that should become a class template.
Array holds a C-array of int with length 10. The type of the C-array and its length are obvious generalization points. Let’s make a class template by introducing a type parameter
T and a non-type parameter
N and playing with them.
Array is parametrized by its type and its size. For size, I used the unsigned integer type
std::size_t (2) that can store the maximum size. To use
std::size_tI have to include the header
<cstddef> (1). So far, the
Array can be instantiated with an
int (3) with a
std::string (4), and with an
Array<int, 3> (5). The following screenshot shows the output of the program.
You can define the member functions of a template inside and outside the class template.
Definitions of Member Functions
Defining the member function inside the class template
When you define the member functions outside the class, you have to specify that it is a template, and you have to specify the full type qualification of the class template. Here is the modified class template
(1) is the member function
getSize of the
Array, defined outside the class. Defining the member function outside the class template becomes challenging if the member function itself is a template.
Member Functions as Templates
A typical example of a generic member function is a templated assignment operator. The reason is straightforward. You want to assign an
Array<T, N> to an
Array<T2, N2> if
T is assignable to
T2 and both arrays have the same size.
Array<float, 5> to an
Array<double, 5> is not valid because both arrays have different types.
floatArr2 (1) is valid because both arrays have the same type. Assigning
doubleArr is an error (2) because both classes have different types. The compiler consequently complains that there is no conversion from
Array<float, 5> to an
Here is a naive implementation of the class Array that supports the assignment of two arrays of the same length. The C-array
elem is intentionally public.
The assignment operator
Array<T, N>& operator = (const Array<T2, N>& arr) accepts arrays that could vary in the underlying type but could not vary in length. Before I show the code in action, I want to improve it.
elem private, it must be a friend of the class.
template<typename, std::size_t> friend class Array (1) declares all instances of Array to friends.
Member Function defined Outside The Class
Defining the generic member function outside the class is quite a job.
In this case, you define a generic member function (1) outside the class body; you have to specify that the class and the member functions are templates. Additionally, you have to specify the full type qualification of the generic member function. So far, the assignment operator is used for types
T2 that is not convertible. Invoking the assignment operator with non-convertible types gives an ugly error message. I should fix this.
Requirements on the Type Parameters
The requirements can be formulated with the type traits library and
static_assert (C++11), or with concepts (C++20). Here are the two variations of the generic assignment operator:
Finally, here is the complete program using the concept
std::convertible_to in the declaration (1) and the definition (2) of the member function.
When I enable (3), the GCC complains that the constraints are unsatisfied.
As you might imagine. I’m not done with class templates. Next time I will write about two tricky details: the inheritance of class templates and the instantiation of member functions of class templates.
The Next PDF-Bundle
I want to resuscitate an old service and create bundles of old posts. I will create the bundles only for my English posts because this is quite a job. These bundles include the posts, all source files, and a CMake file. To make the right decision, you have to make your cross. I will build the pdf bundle with the most votes. The vote is open until 30.05 (including). Vote here.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, and Bhavith C Achar.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,