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


I finished my overview of C++20 in the last post. Now, its time to dive into the details. What can be a better starting point for our journey than concepts?


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

Two Extrems


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 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).


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.


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.


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.


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:


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.


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: Paul Baxter,  Meeting C++, Matt Braun, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Marko, G Prvulovic, Reiner Eiteljörge, Reinhold Dröge, Abernitzke, Richard Ohnemus, Frank Grimm, Sakib, Broeserl, António Pina, Markus Falkner, Darshan Mody, Sergey Agafyin, and Андрей Бурмистров


Thanks in particular to:   crp4



Get your e-book at Leanpub:

The C++ Standard Library


Concurrency With Modern C++


Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages. I also included more than 120 source files.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight in the current and the upcoming concurrency in C++. This insight includes the theory and a lot of practice with more than 140 source files.


Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 700 pages full of modern C++ and more than 260 source files presenting concurrency in practice.


Get your interactive course


Modern C++ Concurrency in Practice

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

educative CLibrary

Based on my book "Concurrency with Modern C++" educative.io created an interactive course.

What's Inside?

  • 140 lessons
  • 110 code playgrounds => Runs in the browser
  • 78 code snippets
  • 55 illustrations

Based on my book "The C++ Standard Library" educative.io created an interactive course.

What's Inside?

  • 149 lessons
  • 111 code playgrounds => Runs in the browser
  • 164 code snippets
  • 25 illustrations
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

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code


Today 6281

Yesterday 7978

Week 30846

Month 185441

All 4806335

Currently are 225 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments