Today, I write about the few remaining rules to templates. Because a collective name is missing, they put the heterogeneous rules to templates in the section other. The rules are about best practices but also about surprises.
Here are the rules for this post.
- T.140: Name all operations with potential for reuse
- T.141: Use an unnamed lambda if you need a simple function object in one place only
- T.143: Don’t write unintentionally nongeneric code
The first rule is about best practices.
Honestly, I’m not so sure why this rule belongs to templates. Maybe templates are about reuse, or the example in the guidelines uses the std::find_if algorithm of the Standard Template Library. Anyway, the rule is fundamental from the code quality perspective.
Imagine you have a vector of records. Each record consists of a name, an address, and an id. You often want to find a record with a specific name; but to make it more challenging, you ignore the case sensitivity of the names.
The struct Rec (line 1) has only public members; therefore, I can use aggregate initialization and initialize all members directly in line (2). In line (3), I use a lambda function to search for the ” smith ” record. First, I check if both names have the same size and second if the characters are identical when compared to case-insensitive.
What’s the problem with the code? The requirement of the case-insensitive comparison of strings is too common, and we should put the solution in an object, give it a name and reuse it.
The function compare_insensitive (line 1) gives a general concept a name. Now, I can use it for a vector of strings (line 2).
I often discuss this in my classes: When should I use a function (function object) or a lambda function? Honestly, I have no easy answer. Here, two meta-rules of code quality contradict:
Sorry, I borrowed the second point from Python. But what does that mean? Imagine you have an old-fashioned Fortran programmer in your team, and he says to you: “Each name must have three characters.” So, you end with the following code.
What does the name igh stand for? igh stands for a id greater hundred. Now, you are forced to document the usage of the predicate.
But If you use a lambda function, the code documents itself.
I had discussions with Fortran programmers about names. Admittedly, more arguments, such as code locality versus code size, speak for or against lambda functions, but “Don’t repeat yourself” versus “Explicit is better than implicit” are my key arguments.
A short example says more than a long explanation. In the following example, I iterate through a std::vector, a std::deque, and a std::list.
The code looks innocent, but the compilation breaks when I want to compile the program. I get about 100 lines of error messages.
At the beginning of the error message, you see it is quite precise: “notGeneric.cpp:10:37: error: no match for ‘operator<‘ (operand types are ‘std::_List_const_iterator“.
What is the issue? The issue is in line (1). The iterator comparison (<) works for the std::vector (line 2) and the std::deque (line 3) but breaks for the std::list (line 4). Each container returns an iterator representing its structure. This is in the case of a std::vector and a std::deque, a random access iterator, and in the case of the std::list, a bidirectional iterator. A look at the iterator categories helps a lot.
The random access iterator category is a superset of the bidirectional iterator category, and the bidirectional iterator category is a superset of the forward iterator category. Now, the issue is obvious. An iterator given by a list does not support the smaller comparison. Fixing the bug is relatively easy. Iterators of each iterator category support the != comparison. Here is the fixed justIterate function template.
By the way, it is typically a bad idea to loop through a container such as I do in the function justIterate. This is a job for an appropriate algorithm of the standard template library.
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, Bhavith C Achar, and Marco Parri Empoli.
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,