C++
Defining concepts
Learn to define C++20 concepts.
What is a concept?
A concept is a named compile-time predicate on template parameters. It arrived with C++20. It tells which types are valid in a readable way.
Example: template<typename T> concept Numeric = std::is_arithmetic_v<T>;. Here Numeric is a concept that accepts arithmetic types. In old C++ template errors used to spread across hundreds of lines; concepts shrink them to one line.
Concepts name template constraints, so the code is both more readable and produces better error messages.
Concept definition syntax
A concept is written as: template<typename T> concept Name = condition;. The condition is a compile-time expression that returns bool.
The condition is either a ready-made concept (std::integral<T>), a requires expression, or a std::is_..._v template variable. Concept names use PascalCase: Addable, Numeric, Hashable. Thanks to this naming, concepts read like documentation.
Exercise Define the Addable concept
Define the Addable concept using the body requires(T a, T b) { a + b; }. In main test it with static_assert(Addable<int>); and print "Addable test passed" with std::cout.
Show example solution
#include <iostream>
#include <concepts>
template<typename T>
concept Addable = requires(T a, T b) {
a + b;
};
int main() {
static_assert(Addable<int>);
std::cout << "Addable test passed";
return 0;
}
Test yourself
-
Which is a concept definition?
- template<typename T> concept Addable = requires(T a, T b) { a + b; };
- template<typename T> auto Addable(T a, T b) { return a + b; }
- template<typename T> struct Addable { };
- concept Addable = int + int;
Show answer
template<typename T> concept Addable = requires(T a, T b) { a + b; }; — A concept is defined with the concept keyword and a template parameter.
-
the concept keyword
template<typename T> ____ Addable = requires(T a, T b) { a + b; };
Show answer
template<typename T> concept Addable = requires(T a, T b) { a + b; };
-
Match each piece to its role
- template<typename T>
- Template parameter
- concept
- Named constraint
- requires(T a, T b)
- Expression check
- a + b
- Valid expression
Next lesson: requires