How do I use Concepts to constrain templates (C++20)?

In C++20, Concepts provide a way to specify constraints on template parameters, allowing you to control the types that can be used with your templates. This can help avoid errors during compilation and improve code clarity by making the intentions of your code explicit.

To use Concepts, you first define a concept using the concept keyword, followed by a boolean expression that describes the requirements of the types. After defining a concept, you can use it to constrain your template parameters, ensuring that only types meeting the requirements can be used.

Here's an example of how to use Concepts to constrain a template:

#include <iostream> #include <concepts> // Define a concept that checks if a type is integral template concept Integral = std::is_integral_v; // A function template that only accepts integral types template T add(T a, T b) { return a + b; } int main() { std::cout << add(5, 10) << std::endl; // Works fine // std::cout << add(5.5, 10.5) << std::endl; // This line would cause a compilation error return 0; }

C++20 Concepts Templates Type Constraints Integral Types