C++ 20: Concepts

Written by on September 19, 2021 in C++, Programming with 0 Comments

Concepts, introduced in C++20, are predicates that act as contraints on template parameters. As you would expect, the nice thing is that the constraint checking happens as part of template instantiation at compile time and not at run time!

Since templates can have type as well as non-type parameters, Concepts can be applied to both these parameter categories.

Let us first look at an example where a Concept is associated with a type parameter:

Constraint on Type

Constraint on Type

In this example, we are defining a Concept that requires a type to be of “pointer”. This makes use of the standard library predicate is_pointer_v<T>. 

Lines 14 – 18 define a function “foo” that takes a PointerType argument. Notice how the template declaration constrains the type argument.

Interestingly, there are 3 other equivalent ways to specify the constraint:

Alternative Syntax

Alternative Syntax

The following code fragment shows how we can call the “foo” function by passing pointers. 

Calling "foo()"

Calling “foo()”

Any attempt to pass a non-pointer will trigger compiler error. So if we uncomment line 70, we will get a compiler error like the following:

Invalid Argument Type Error

Invalid Argument Type Error

Our next example is about defining a Concept that applies to a non-type template argument.

Concept Applied to Non-type

Concept Applied to Non-type

Here, we are defining a predicate on an integer, constraining it to be between 5 and 10 (both included).  Notice the use of nested “requires”.

Lines 72-73 show how this is used.

Example

Example

If we uncomment lines 74 and 75, we will get a compiler error:

Compiler Error

Compiler Error

As I mentioned earlier, Concepts are checked at compile-time, and that is a great thing!

Concepts are a major addition to C++20 and I have just scratched the surface. For a formal reference, please visit this page.

You can download the example file here. I used Visual Studio Pro 2019 Version 16.11.2 for compiling the example. It is important to select “ISO C++20 Standard” as the “C++ Language Standard” property when building the project.

Have a nice weekend!

Tags: ,

Subscribe

If you enjoyed this article, subscribe now to receive more just like it.

Subscribe via RSS Feed

Leave a Reply

Your email address will not be published.

Top