Search⌘ K
AI Features

Four Ways to Use Concepts

Explore four distinct ways to use concepts in C++20, including requires clauses and constrained template parameters, to write safer and more generic template functions. Understand how concepts improve type constraints and template behavior for integral types.

Before discussing the four ways to use a concept, look at the code below. Here, I apply the predefined concept std::integral in all four ways.

C++
#include <concepts>
#include <iostream>
// Requires clause
template<typename T>
requires std::integral<T>
auto gcd(T a,T b) {
if( b == 0 ) return a;
else return gcd(b, a % b);
}
// Trailing requires clause
template<typename T>
auto gcd1(T a,T b) requires std::integral<T> {
if( b == 0 ) return a;
else return gcd1(b, a % b);
}
// Constrained template parameter
template<std::integral T>
auto gcd2(T a,T b) {
if( b == 0 ) return a;
else return gcd2(b, a % b);
}
// Abbreviated function template
auto gcd3(std::integral auto a, std::integral auto b) {
if( b == 0 ) return a;
else return gcd3(b, a % b);
}
int main() {
std::cout << '\n';
std::cout << "gcd(100, 10)= " << gcd(100, 10) << '\n';
std::cout << "gcd1(100, 10)= " << gcd1(100, 10) << '\n';
std::cout << "gcd2(100, 10)= " << gcd2(100, 10) << '\n';
std::cout << "gcd3(100, 10)= " << gcd3(100, 10) << '\n';
std::cout << '\n';
}

Thanks to the header <concepts> at line 1, I can use the concept std::integral. The concept is fulfilled if T is the type integral. The function name gcd stands for the greatest common divisor algorithm based on the Euclidean algorithm.

Here are the four ways to use concepts:

  • Requires clause (at line 5
...