...

/

Use-cases for Concepts

Use-cases for Concepts

Discover use-cases of concepts in C++20.

First and foremost, concepts are compile-time predicates. A compile-time predicate is a function that is executed at compile-time and returns a boolean.

Before I dive into the various use-cases of concepts, I want to demystify concepts and present them simply as functions returning a boolean at compile time.

Compile-time predicates

A concept can be used in a control structure, which is executed at run time or compile-time. Run the code below.

Press + to interact
#include <compare>
#include <iostream>
#include <string>
#include <vector>
struct Test{};
int main() {
std::cout << "\n";
std::cout << std::boolalpha;
std:: cout << "std::three_way_comparable<int>: "
<< std::three_way_comparable<int> << "\n";
std::cout << "std::three_way_comparable<double>: ";
if (std::three_way_comparable<double>) std::cout << "True";
else std::cout << "False";
std::cout << "\n\n";
static_assert(std::three_way_comparable<std::string>);
std::cout << "std::three_way_comparable<Test>: ";
if constexpr(std::three_way_comparable<Test>) std::cout << "True";
else std::cout << "False";
std::cout << '\n';
std::cout << "std::three_way_comparable<std::vector<int>>: ";
if constexpr(std::three_way_comparable<std::vector<int>>) std::cout << "True";
else std::cout << "False";
std::cout << '\n';
}

In the program above, I use the concept ...