C++ Concepts

Concepts are a c++ 20 way to constrain your template functions to specific types.

Prior to C++ 20 you could constrain your template functions by using a static assert:

template <typename T> T maximum(T a, T b) {
    static_assert(std::is_integral_v<T>, "Arguments must be integral");
    return (a > b) ? a : b;
}

Since C== 20 you can use concepts instead, you need to include the library concepts. There are multiple syntaxes for using concepts in C++:

template <typename T>
requires std::integral<T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}

or:

template <typename T>
T maximum(T a, T b) requires std::integral<T> {
    return (a > b) ? a : b;
}

or

template <std::integral T>
T maximum(T a, T b) {
    return (a > b) ? a : b;
}

You can even use them if you prefer to use auto instead of function templates:

auto maximum(std::integral auto a, std::integral auto b) {
    return (a > b) ? a : b;
}

As well as using the built in concepts, you can create your own. When you create your own ones, it just checks for valid syntax, it doesn’t actually perform the operation. The syntax is as follows:

template <typename T>
concept Multipliable = requires(T a, T b} {
    a * b -> std::convertible_to<long>;
};

You can check for the value of an expression by nesting a concept:

template <typename T>
concept TinyInt = requires(T a} {
    sizeof(a) <= 4;
    requires  sizeof(a) <= 4 ;
};

They can be combined using logical operators. For example:

template <typename T>
T maximum (T a, T b) requires std::integral<T> || std::floating_point<T> {

 

 

 

 

 

 

 

 

 

 

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.