Search⌘ K

Defining Concepts

Explore how to define your own concepts in C++20 to enhance template programming and enforce type safety. Understand the syntax for concept definitions, how to use compile-time predicates and logical combinations, and apply practical examples like Integral and SignedIntegral concepts to improve your code.

When the concept you are looking for is not one of the predefined concepts in C++20, you must define your own concept. In this section, I will define a few concepts which will be distinguishable from the predefined concepts through the use of CamelCase syntax. Consequently, my concept for a signed integral is named SignedIntegral, whereas the C++ standard concept goes by the name signed_integral.

The syntax for defining a concept is straightforward:

C++
template <template-parameter-list>
concept concept-name = constraint-expression;

A concept definition starts with the keyword template and has a template parameter list. The second line is more interesting. It uses the keyword concept followed by the concept name and the constraint expression. A constraint-expression can either be:

  • A logical combination of other concepts ...