Examples of Constraints
Example 1:
The below code demonstrates the usage of constraints in C++ to restrict the valid types that can be used with function templates.
C++
// C++ program to illustrate the constrains #include <iostream> #include <type_traits> using namespace std; // Function template with constraint using requires clause template < typename T> requires is_integral_v<T> void print_integer(T value) { cout << "The integer value is: " << value << endl; } // Concept definition template < typename T> concept Printable = requires(T value) { cout << value << endl; }; // Function template with concept as a constraint template <Printable T> void print(T value) { cout << "The printable value is: " << value << endl; } int main() { // Call the print_integer function with an integer // argument print_integer(42); // Call the print function with a string argument print( "Hello, World!" ); } |
Output
The integer value is: 42 The printable value is: Hello, World!
Violations of constraints are typically detected during the template instantiation process in C++. The compiler generates an error message for the specific constraint that has been violated.
Example 2:
C++
// C++ program to illustrate the voilation in specified // constrains for template arguments #include <concepts> #include <iostream> template < typename T> requires integral<T> void foo(T value) { cout << "Value: " << value << endl; } int main() { // Valid usage, T = int (integral type) foo(5); // Error: Violation of constraint, T = double // (not an integral type) foo(3.14); return 0; } |
Output
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