C++20: Define Concepts

With this post, I start my last very exciting topic to concepts: define your concepts. Consequentially, I answer the questions I opened in previous posts.

 

TimelineCpp20Concepts

First and foremost, most of the concepts I define are already available in the C++ 20 draft. Therefore, there is no need to define them. To distinguish my concepts from the predefined concepts, I capitalize them. To remind you, my previous post gave an overview of the predefined concepts: C++20: Concepts - Predefined Concepts.

Defining concepts

There are two typical ways to define concepts: use the direct definition or use requires-expressions. 

Direct definition

The syntactic form changed a little bit from the syntax based on the concepts TS (Technical Specification) to the proposed syntax for the C++20 standard. 

Concepts TS

template<typename T>
concept bool Integral(){
    return std::is_integral<T>::value;
}

C++20 standard 

template<typename T>
concept Integral = std::is_integral<T>::value;

 

The C++20 standard syntax is less verbose. Both use under the hood the function std::is_integral<T>::value from the C++11 type-traits library. T fulfills the concept if the compile-time predicate std::integral<T>::value evaluates to true. Compile-time predicate means, that the function runs at compile-time and returns a boolean. Since C++17, you can write std::integral<T>::value less verbose: std::integral_v<T>. 

I'm not sure if the two terms variable concept for direct definition and function concept for requires-expressions are still used but they help to keep the difference between the direct definition and the requires-expressions in mind. 

 

I skip the example to the usage of the concept Integral. If you are curious, read my previous post: C++ 20: Concepts, the Placeholder Syntax

Requires-expressions

Analogous to the direct definition, the syntax of requires-expressions changed also from the concepts TS to the proposed draft C++20 standard. 

Concepts TS 

template<typename T>
concept bool Equal(){
    return requires(T a, T b) {
        { a == b } -> bool;
        { a != b } -> bool;
   };
}

C++20 standard

template<typename T>
concept Equal =
    requires(T a, T b) {
        { a == b } -> bool;
        { a != b } -> bool;
    };

 

As before, the C++20 syntax is more concise. T fulfills the concept if the operator == and != are overloaded and return a boolean. Additionally, the types of a and b have to be the same.

The concept Equal

Now, it's time to use the concept Equal

// conceptsDefintionEqual.cpp

#include <iostream>

template<typename T>
concept Equal =
    requires(T a, T b) {
        { a == b } -> bool;
        { a != b } -> bool;
};


bool areEqual(Equal auto a, Equal auto b) {                     // (1)            
  return a == b;
}

/*

struct WithoutEqual{
  bool operator==(const WithoutEqual& other) = delete;
};

struct WithoutUnequal{
  bool operator!=(const WithoutUnequal& other) = delete;
};

*/

int main() {
  
  std::cout << std::boolalpha << std::endl;
  
  std::cout << "areEqual(1, 5): " << areEqual(1, 5) << std::endl;
  
  /*
  
  bool res = areEqual(WithoutEqual(),  WithoutEqual());
  
  bool res2 = areEqual(WithoutUnequal(),  WithoutUnequal());
  
  */
  
  std::cout << std::endl;
  
}

I used the concept of Equal in the function areEqual (line 1). To remind you. By using a concept as a function parameter, the compiler creates under the hood a function template, with by the concept specified constraints on the parameters. To get more information to this concise syntax, read my already mentioned post: C++ 20: Concepts, the Placeholder Syntax

 

The output is not so exciting: 

conceptsDefinitionEqual

Now, it becomes exciting. What happens, if I use the types WithoutEqual and WithoutUnequal. I set intentionally the ==  operator and the != operator to delete. The compiler complains immediately that both types do not fulfill the concept of Equal

conceptsDefinitionEqualError

When you look carefully at the error message, you see the reason: (a == b) would be ill-formed and (a != b) would be ill-formed. 

Before I continue I have to make a short detour. You can skip the detour if you don't want to compile the program.

The Implementation status of concepts

I faked the output of the program conceptsDefinitonEqual.cpp. The output is from the Concepts TS implementation of GCC. At this point in time, there is no C++20 standard-conforming implementation of the concepts syntax available.

  • The latest Microsoft compiler supports the C++20 syntax for defining concepts, but not the placeholder syntax I used for the function areEqual. 
  • The GCC compiler supports the placeholder syntax I used but not the C++20 draft syntax for defining concepts. 

From Equal to Ord

I already mentioned in the previous post C++20: Two Extremes and the Rescue with Concepts, that concepts at first remind me of Haskell's type classes. Type classes in Haskell are interfaces for similar types. The main difference to concepts is, that a type such as Int in Haskell has to be an instance of a type class and, therefore, to implement the type class. On the contrary, the compiler checks with concepts  if a type fulfills a concept.

 

Here is a part of the Haskell type class hierarchy.

haskellsTypeclasses

This is my crucial observation. Haskell supports the type class Eq. When you compare the definition of the type class Eq and the concept Equal, they look quite similar.

The type class Eq

class Eq a where
    (==) :: a -> a -> Bool
    (/=) :: a -> a -> Bool

 

The concept Equal

template<typename T>
concept Equal =
    requires(T a, T b) {
        { a == b } -> bool;
        { a != b } -> bool;
    };

Haskell's type class requires from its instances such as Int

  • that they have the equal == and inequal /= operation that returns a Bool.
  • that both operations take two arguments (a -> a) of the same type.

Let's look once more on the type class hierarchy of Haskell. The type class Ord is a refinement of the type class Eq. The definition of Ord makes this clear.

class Eq a => Ord a where
    compare :: a -> a -> Ordering
    (<) :: a -> a -> Bool
    (<=) :: a -> a -> Bool
    (>) :: a -> a -> Bool
    (>=) :: a -> a -> Bool
    max :: a -> a -> a

 

The most interesting point about the definition of the type class Ord is their first line. An instance of the type class Ord has to be already an instance of the type class EqOrdering is an enumeration having the values EQ, LT, and GT. This refinement of type classes is highly elegant.

Here is the challenge for the next post. Can concepts be refined in a similarly elegant way? 

What's next? 

In my next post, I accept the challenge to refine the concept of Equal. Additionally, I write about the import concepts Regular and Semiregular and, of course, I define them. 

 

 

 

Thanks a lot to my Patreon Supporters: Meeting C++, Matt Braun, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Richard Ohnemus, Frank Grimm, Sakib, Broeserl, António Pina, Markus Falkner, Darshan Mody, Sergey Agafyin, Андрей Бурмистров, Jake, GS, and Lawton Shoemake.

 

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

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

Visitors

Today 1171

Yesterday 7707

Week 24299

Month 229346

All 4850240

Currently are 165 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments