C++ Core Guidelines: Rules for the Definition of Concepts

Contents[Show]

Although rule T.11 states: Whenever possible, use standard concepts you sometimes have to define your concepts. This post gives you rules to do it.

 definition 390785 1280

The C++ core guidelines have nine rules for defining concepts. Seven of them have content. Here are the first four for today.

Let's see how to define concepts

T.20: Avoid “concepts” without meaningful semantics

This rule is quite obvious, but what does meaningful semantic mean? Meaningful semantics are not just simple constraints such as has_plus but concepts such as Number, Range, or InputIterator. 

For example, the following concept Addable requires has_plus and is, therefore, also fulfilled by a string.

 

template<typename T>
concept Addable = has_plus<T>;    // bad; insufficient

template<Addable N> auto algo(const N& a, const N& b) // use two numbers
{
    // ...
    return a + b;
}

int x = 7;
int y = 9;
auto z = algo(x, y);   // z = 16

string xx = "7";
string yy = "9";
auto zz = algo(xx, yy);   // zz = "79"

 

I assume this was not your intention because the function template algo should accept arguments that model numbers and not just Addable. The solution is quite simple. Define and use a concept Number with a meaningful semantic.

template<typename T>
// The operators +, -, *, and / for a number 
// are assumed to follow the usual mathematical rules
concept Number = has_plus<T>
                 && has_minus<T>
                 && has_multiply<T>
                 && has_divide<T>;

template<Number N> auto algo(const N& a, const N& b)
{
    // ...
    return a + b;
}

 

Now the invocation of algo with a string would give an error. The next rule is a particular case of this rule.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Be part of my mentoring programs:

 

 

 

 

Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.

T.21: Require a complete set of operations for a concept

First of all, what is a complete set of operations? Here are two complete sets for Arithmetic and Comparable.

  • Arithmetic: +, -, *, /, +=, -=, *=, /=
  • Comparable: <, >, <=, >=, ==, !=

Do you want to know what the acronym POLA stands for? It stands for Principle Of Least Astonishment. You can easily break this principle of good software design if you implement just a partial set of operations.

Here is an auspicious example from the guidelines.  The concept Minimal in this case, supports==, < and +.

void f(const Minimal& x, const Minimal& y)
{
    if (!(x == y)) { /* ... */ }    // OK
    if (x != y) { /* ... */ }       // surprise! error

    while (!(x < y)) { /* ... */ }  // OK
    while (x >= y) { /* ... */ }    // surprise! error

    x = x + y;          // OK
    x += y;             // surprise! error
}

T.22: Specify axioms for concepts

First of all: What is an axiom? Here is my definition from Wikipedia:

  • An axiom or postulate is a statement that is taken to be true, to serve as a premise or starting point for further reasoning and arguments.

Because C++ does not support axioms, you must express them with comments. If C++ does support them in the future, you can remove the comment symbol // in front of the axiom in the following example.

template<typename T>
    // axiom(T a, T b) { a + b == b + a; a - a == 0; a * (b + c) == a * b + a * c; /*...*/ }
    concept Number = requires(T a, T b) {
        {a + b} -> T;  
        {a - b} -> T;
        {a * b} -> T;
        {a / b} -> T;
    }

 

The axiom means, in this case, that the number follows the mathematical rules. In contrast, the concept requires that a Number has to support the binary operations +, -, *, and / and that the result is convertible to T. T is the type of argument.

T.23: Differentiate a refined concept from its more general case by adding new use patterns

If two concepts have the same requirements, they are logically equivalent. This means the compiler can't distinguish them and may not automatically choose the correct one during overload resolution.

To make the rule clear, here is a simplified version of the concept BidirectionalIterator and the refined concept RandomAccessIterator.

 

template<typename I>
concept bool BidirectionalIterator = ForwardIterator<I> && 
                                     requires(I iter){ 
                                         --iter;  
                                         iter--; 
                                     }  

template<typename I>
concept bool RandomAccessIterator = BidirectionalIterator<I> && 
Integer<N> && requires(I iter, I iter2, N n){ iter += n; // increment or decrement an iterator iter -= n; n + iter; // return a temp iterator iter + n; iter - n; iter[n]; // access the element
iter1 - iter2; // subtract two iterators
iter1 < iter2; // compare two iterators
iter1 <= iter2;
iter1 > iter2;
iter1 >= iter2; }

 

std::advance(i, n) increments a given iterator i by n elements. Depending on the value of n, the iterator is incremented or decremented. When the iterator i is bidirectional iterator, std::advance has to step n times one element forward or backward. But when the iterator i is a random access iterator, just n is added to the iterator.

 

template<BidirectionalIterator I>
void advance(I& iter, int n){...}

template<RandomAccessIterator I>
void advance(I& iter, int n){...}

std::list<int> lst{1, 2, 3, 4, 5, 6, 7, 8, 9};
std::list<int>::iterator listIt = lst.begin();
std::advance(listIt, 2);   // BidirectionalIterator

std::vector<int> vec{1, 2, 3, 4, 5, 6, 7, 8, 9};
std::vector<int>::iterator vecIt = vec.begin();
std::advance(vecIt, 2);    // RandomAccessIterator

 

In the case of the std::vector<int>, vec.begin() returns a random access iterator and, therefore, the fast variant of std::advance is used.

Each container of the STL creates an iterator specific to its structure. Here is the overview:

IteratorCategories

What's next?

Three rules to the definition of concepts are left. In particular, the following rule, "T.24: Use tag classes or traits to differentiate concepts that differ only in semantics." sounds pretty attractive. Let's see in the next post what a tag class or traits class is. 

 

 

 

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, Animus24, 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, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

 

My special thanks to Take Up Code TakeUpCode 450 60

 

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.

  • 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++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

Tags: Concepts

Stay Informed about my Mentoring

 

Mentoring

English 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

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

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 2195

Yesterday 4344

Week 39073

Month 19319

All 12097528

Currently are 135 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments