Four Ways to Use Concepts
Learn four ways to use a concept in C++20.
We'll cover the following...
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.
Press + to interact
#include <concepts>#include <iostream>// Requires clausetemplate<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 clausetemplate<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 parametertemplate<std::integral T>auto gcd2(T a,T b) {if( b == 0 ) return a;else return gcd2(b, a % b);}// Abbreviated function templateauto 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 ...