Defining concepts
- C++ course
- Advanced
- Lesson 61/83
- 5 min
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.
Practice 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.
Starter code
#include <iostream>
#include <concepts>
// Define the Addable concept here
int main() {
// Test for int and print a message
return 0;
}Sample 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;
}Expected output
Addable test passed
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a concept definition?
- template<typename T> concept Addable = requires(T a, T b) { a + b; }; Correct answer
- template<typename T> auto Addable(T a, T b) { return a + b; }
- template<typename T> struct Addable { };
- concept Addable = int + int;
Explanation: A concept is defined with the concept keyword and a template parameter.
2 the concept keyword
template<typename T> ____ Addable = requires(T a, T b) { a + b; };
template<typename T> concept Addable = requires(T a, T b) { a + b; };
Explanation: The concept keyword starts a concept definition.
3 Match each piece to its role
| Term | Meaning |
|---|---|
template<typename T> |
Template parameter |
concept |
Named constraint |
requires(T a, T b) |
Expression check |
a + b |
Valid expression |