C++20: Two Extremes and the Rescue with Concepts
I finished my overview of C++20 in the last post. Now, it’s time to dive into the details. What can be a better starting point for our journey than concepts?
I must confess: I’m a big fan of concepts and, therefore, biased. Anyway, let’s start with a motivating example.
Two Extremes
Until C++20, we have in C++ two diametral ways to think about functions or classes. Functions or classes can be defined on specific types or on generic types. In the second case, we call them function or class templates. What is wrong with each way?
Too Specific
It’s quite a job to define a function or class for each specific type. To avoid that burden, type conversion often comes to our rescue. What seems like rescue is often a curse.
// tooSpecific.cpp #include <iostream> void needInt(int i){ std::cout << "int: " << i << std::endl; } int main(){ std::cout << std::boolalpha << std::endl; double d{1.234}; // (1)N std::cout << "double: " << d << std::endl; needInt(d); // (2) std::cout << std::endl; bool b{true}; // (3) std::cout << "bool: " << b << std::endl; needInt(b); // (4) std::cout << std::endl; }
In the first case (line 1), I start with a double and end with an int (line 2). In the second case, I start with a bool (line 3) and also end with an int (line 4).
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
Narrowing Conversion
Invoking getInt(int a)
with a double g
gives you a narrowing conversion. Narrowing conversion is conversion which a loss of accuracy. I assume this is not what you want.
Integral Promotion
But the other way around is also not better. Invoking getInt(int a) with a bool promotes the bool to int. Surprised? Many C++ developers don’t know which type they will get when they add to bool’s.
template <typename T> auto add(T first, T second){ return first + second; } int main(){ add(true, false); }
C++ Insights shows you the truth.
The template instantiation of the function template add creates a full specialization (lines 6 – 12) with the return type int.
My firm belief is that we need, for convenience reasons, the entire magic of conversions in C/C++ to deal with the fact that functions only accept specific types.
Okay. Let’s do it the other way around. Write not specifically, but write generically. Maybe, writing generic code with templates is our rescue.
Too Generic
Here is my first try. Sorting is such a generic idea. It should work for each container if the elements of the container are sortable. Let’s apply std::sort to a std::list.
// sortList.cpp #include <algorithm> #include <list> int main(){ std::list<int> myList{1, 10, 3, 2, 5}; std::sort(myList.begin(), myList.end()); }
WOW! This is what you get when I try to compile the small program.
I don’t even want to decipher this message. What is going wrong? Let’s look closer at the signature of the used overload of std::sort.
template< class RandomIt > void sort( RandomIt first, RandomIt last );
std::sort uses strange-named arguments such as RandomIT. RandomIT stands for a random access iterator. This is why the overwhelming error message, for which templates are infamous. A std::list provides only a bidirectional iterator, but std:sort requires a random access iterator. The structure of a std::list makes this obvious.
When you study carefully the documentation on cppreference.com page to std::sort, you find something exciting: type requirements on std::sort.
Concepts to the Rescue
Concepts are the rescue because they put semantic constraints on a template parameter.
Here are the already mentioned type requirements on std::sort.
- The dereferenced
RandomIt
must meet the requirements of MoveAssignable and MoveConstructible. -
Compare
must meet the requirements of Compare.
The type requirements on std::sort are concepts. For a short introduction to concepts, read my post C++20: The Big Four. In particular, std::sort requires a LegacyRandomAccessIterator. Let’s have a closer look at the concept. I polished the example from cppreference.com a little bit.
template<typename It> concept LegacyRandomAccessIterator = LegacyBidirectionalIterator<It> && // (1) std::totally_ordered<It> && requires(It i, typename std::incrementable_traits<It>::difference_type n) { { i += n } -> std::same_as<It&>; // (2) { i -= n } -> std::same_as<It&>; { i + n } -> std::same_as<It>; { n + i } -> std::same_as<It>; { i - n } -> std::same_as<It>; { i - i } -> std::same_as<decltype(n)>; { i[n] } -> std::convertible_to<std::iter_reference_t<It>>; };
Here is the critical observation. A type It supports LegacyRandomAccessIterator if it supports LegacyBidirectionalIterator (line 2) and all other requirements. For example, the requirement in line 2 means that for a value of type It: { i += n } is a valid expression, and it returns an I&. To complete my story, std::list support a LegacyBidirectionalIterator.
Admittedly, this section was quite technical. Let’s try it out. With concepts, you could expect a concise error message such as the following:
Of course, this error message was fake because no compiler implements the C++20 syntax for concepts. MSVC 19.23 support them partially, and GCC is a previous version of concepts. cppreference.com gives more details about the current state of concepts.
Did I mention that GCC supports the previous version of concepts?
The Long, Long History
I heard about the first time about concepts around 2005 – 2006. They reminded me of Haskell type classes. Type classes in Haskell are interfaces for similar types. Here is a part of Haskell type classes hierarchy.
But C++ concepts are different. Here are a few observations.
- In Haskell, a type has to be an instance of a type class. In C++20, a type has to fulfill the requirements of a concept.
- Concepts can be used on non-type arguments of templates. For example, numbers such as 5 are non-type arguments. When you want a std::array of int’s with five elements, use the non-type argument 5: std::array<int, 5> myArray.
- Concepts add no run-time costs.
Initially, concepts should be the critical feature of C++11, but they were removed in the standardization meeting in July 2009 in Frankfurt. The quote from Bjarne Stroustrup speaks for itself: “The C++Ox concept design evolved into a monster of complexity.“. The next try was unsuccessful a few years later: concepts lite was removed from the C++17 standard. Finally, they are part of C++20.
What’s next?
Of course, my next post is about concepts. I present many examples of what semantic constraints on template parameters mean.
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, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, 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, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, and Honey Sukesan.
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 | |
My special thanks to SHAVEDYAKS |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Modernes C++ Mentoring,
Leave a Reply
Want to join the discussion?Feel free to contribute!