Examples of Concepts in C++
Example 1:
The below code demonstrates the usage of concepts in C++ to define and apply requirements on template arguments.
C++
// C++ Program to illustrate the use of concept to define // constraints #include <iostream> #include <iterator> #include <type_traits> #include <vector> using namespace std; // Define the Container concept template < typename T> concept Container = requires(T t) { { std::size(t) } ->std::same_as<std:: size_t >; { std::begin(t) } ->std::same_as< typename T::iterator>; { std::end(t) } ->std::same_as< typename T::iterator>; }; // Define the ContainerWrapper class that works with // containers satisfying the // Container concept template <Container C> class ContainerWrapper { public : ContainerWrapper(C c) : container(c) { } // Print the elements of the container void print() { for ( auto it = std::begin(container); it != std::end(container); ++it) { cout << *it << " " ; } cout << endl; } private : C container; }; int main() { // Create a vector container vector< int > v{ 1, 2, 3 }; // Instantiate a ContainerWrapper object with the vector ContainerWrapper wrapper(v); // Print the elements of the container using the // ContainerWrapper wrapper.print(); } |
Output
1 2 3
Note: Concepts in C++ can not refer to themselves in a recursive manner.
Example 2:
The below code demonstrates errors that occur when we define recursive concepts.
C++
template < typename T> // Attempting recursive reference concept RecursiveConcept = RecursiveConcept<T*>; template < typename T> void foo(T value) requires RecursiveConcept<T> { // Code } int main() { // Will result in a compiler error foo(42); return 0; } |
The above code will result in an error as we have defined a concept RecursiveConcept in the code that refers to itself that is not allowed in C++.
Concepts can be named in an id-expression. When we use the concept in an id-expression, the value of the id-expression is determined by whether the constraint expression of the concept is satisfied by the template argument.
If the constraint expression is satisfied by the template argument, the value of the id-expression is true, else it is false.
Constraints and Concepts in C++ 20
In this article, we will learn about the constraints and concepts with the help of examples in a simple way. So, it is a feature that was introduced in the latest version i.e. C++20 that specifies requirements on template arguments and enables more expressive and readable code.
Contact Us