C++ - Concept example

less than 1 minute read

C++20 introduced concept. The following code shows the example of using concept.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <concepts>
#include <iostream>
#include <vector>

// Define a concept that expects a .size() member function
template<typename T>
concept HasSize = requires(T a) {
    { a.size() } -> std::convertible_to<std::size_t>;
};

// Use the concept to constrain a function
void print_size(const HasSize auto& container) {
    std::cout << "Size is: " << container.size() << '\n';
}

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    print_size(vec);  // OK! vector has size()

    std::string str = "hello";
    print_size(str);  // OK! string also has size()

    // int x = 5;
    // print_size(x); // Compile-time error! int doesn't have size()
}

Categories:

Updated: