Concepts (C++20)

Constraining templates

Interview Relevant: Modern template design

Concepts (C++20)

Named requirements for template parameters.

Code Examples

Concepts for cleaner template constraints.

cpp
1#include <concepts>
2
3// Using standard concepts
4template<std::integral T>
5T add(T a, T b) {
6    return a + b;
7}
8
9// Define custom concept
10template<typename T>
11concept Printable = requires(T t) {
12    { std::cout << t } -> std::same_as<std::ostream&>;
13};
14
15template<Printable T>
16void print(const T& value) {
17    cout << value << endl;
18}
19
20// Concept with multiple requirements
21template<typename T>
22concept Container = requires(T t) {
23    t.begin();
24    t.end();
25    t.size();
26    typename T::value_type;
27};
28
29template<Container C>
30void processContainer(const C& c) {
31    for (const auto& elem : c) { }
32}
33
34// Concept as function constraint
35void process(auto x) requires std::integral<decltype(x)> {
36    // ...
37}

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In