C++20 Concepts Guide
C++20 Concepts Guide
C++20 introduced concepts to provide a way to specify constraints on template parameters. They
Key Features:
- Better Compiler Diagnostics: Error messages for templates are more intuitive.
Syntax:
template<typename T>
Example:
#include <concepts>
#include <iostream>
template<typename T>
a++;
};
void printIncrementable(Incrementable auto value) {
int main() {
int x = 10;
printIncrementable(x); // Valid
return 0;
}
2. Common Concepts in the Standard Library
C++20 provides pre-defined concepts in the standard library for common use cases.
Example:
#include <concepts>
Example:
#include <concepts>
#include <iostream>
}
void acceptFloatingPoint(std::floating_point auto value) {
int main() {
acceptIntegral(42); // Works
acceptFloatingPoint(3.14); // Works
return 0;
}
3. Writing Custom Concepts
Creating custom concepts allows you to define specific constraints for template parameters.
2. Use requires to specify requirements like valid expressions, member functions, etc.
#include <concepts>
#include <iostream>
template<typename T>
{ a + b } -> std::same_as<T>;
};
template<Addable T>
T add(T a, T b) {
return a + b;
int main() {
return 0;
template<typename T>
{ x + x } -> std::same_as<T>;
{ x * x } -> std::same_as<T>;
x == x;
x != x;
};