What are concepts in C++20?
A concept is a compile time condition on a type. You use it to say what a template needs.
#include <concepts>
#include <iostream>
#include <string>
template <typename T>
concept Printable = requires(T x) { std::cout << x; };
template <Printable T>
void show(const T& x) { std::cout << x << '\n'; }
template <std::integral T>
T half(T x) { return x / 2; }
int main() {
show(42);
show(std::string("text"));
std::cout << half(9) << '\n';
}
42
text
4
#include <concepts>
template <std::integral T>
T half(T x) { return x / 2; }
int main() {
half(3.5);
}
Wrong.cpp: In function 'int main()':
Wrong.cpp:7:9: error: no matching function for call to 'half(double)'
7 | half(3.5);
| ~~~~^~~~~
• there is 1 candidate
• candidate 1: 'template<class T> requires integral<T> T half(T)'
Wrong.cpp:4:3:
4 | T half(T x) { return x / 2; }
| ^~~~
• template argument deduction/substitution failed:
• constraints not satisfied
In file included from Wrong.cpp:1:
• /usr/local/include/c++/16.2.0/concepts: In substitution of 'template<class T> requires integral<T> T half(T) [with T = double]':
• required from here
Wrong.cpp:7:9:
7 | half(3.5);
| ~~~~^~~~~
• required for the satisfaction of 'integral<T>' [with T = double]
/usr/local/include/c++/16.2.0/concepts:109:13:
109 | concept integral = is_integral_v<_Tp>;
| ^~~~~~~~
• the expression 'is_integral_v<_Tp> [with _Tp = double]' evaluated to 'false'
/usr/local/include/c++/16.2.0/concepts:109:24:
109 | concept integral = is_integral_v<_Tp>;
| ^~~~~~~~~~~~~~~~~~
The error says clearly that double does not satisfy std::integral, instead of 50 lines of template messages. See Templates.
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |