Skip to main content
Share Your Experience: Take the 2024 Developer Survey

For code that defines concepts to describe types' supported operations or makes heavy use of them in generic programming.

C++20 introduced Concepts to the language, which are compile-time predicates on types, and can be used to constrain template type parameter matching.

As an example, the std::integral concept can be used to provide a constrained print() function that handles integer values differently to other types:

#include <concepts>
#include <iostream>
 
void print(std::integral auto i) {
    std::cout << "Integral: " << i << '\n';
}
 
void print(auto x) {
    std::cout << "Non-integral: " << x << '\n';
}
 
int main()
{
    print( 'o' ); static_assert( std::integral<char> );
    print( 007 ); static_assert( std::integral<int> );
    print( 2e2 ); static_assert( !std::integral<float> );
    print("∫∫∫"); static_assert( !std::integral<decltype("")> );
}

This produces:

Integral: o
Integral: 7
Non-integral: 200
Non-integral: ∫∫∫

References: