C++20: Two Extremes and the Rescue with Concepts

Contents[Show]

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?

TimelineCpp20Concepts

I have to confess: I'm a big fan of concepts and, therefore, biased. Anyway, let's start with a motivating example.

Two Extremes

TwoExtrems

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 to function or class templates. What is wrong with each way?

Too Specific

It's quite a job to define for each specific type a function or a class. To avoid that burden, type conversion comes often 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 end also with an int (line 4).

tooSpecific

Narrowing Conversion

Invoking getInt(int a) with a double gives you 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.

addGeneric

The template instantiation of the function template add creates a full specialisation (lines 6 - 12) with the return type int.

My strong 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 specific, 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.

sortList

I don't even want to decipher this message. What is going wrong? Let's have a closer look 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 the reason for 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.

list

When you study carefully the documentation on cppreference.com page to std::sort, you find something very interesting: type requirements on std::sort.

Concepts to the Rescue

Concepts are the rescue because they put semantic constraints on template parameter.

Here are the already mentioned type requirements on std::sort.

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 key observation. A type It supports the concept  LegacyRandomAccessIterator if it supports the concept 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 on:

listError

Of course, this error message was a fake, because no compiler implements the C++20 syntax for concepts. MSVC 19.23 support them partially, and GCC a previous version of concepts. cppreference.com gives more details to the current state of concepts.

Did I mention that GCC supports the previous version of concepts?

The long, long History

I heard the first time about concepts around 2005 - 2006. The reminded me of Haskell type classes. Type classes in Haskell are interfaces for similar types. Here is a part of Haskell type classes hierarchy.

haskellsTypeclasses

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 fulfil 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 to have a std::array of int's with 5 elements, you use the non-type argument 5: std::array<int, 5> myArray.
  • Concepts add no run-time costs.

Originally, concepts should be the key feature of C++11, but they were removed in the standardisation 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.". A few years later, the next try was also not successful: concepts lite were 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, what semantic constraints on template parameter mean.

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, Tornike Porchxidze, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Satish Vangipuram, and Michael Dunsky.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, and Said Mert Turkal.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmSmall

Tags: concepts

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 5178

Yesterday 7071

Week 42154

Month 202828

All 6851520

Currently are 166 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments