...

/

Abbreviated Function Templates

Abbreviated Function Templates

Learn how to use a function declaration as a function template using a placeholder.

We'll cover the following...

With C++20, you can use an unconstrained placeholder (auto) or a constrained placeholder (concept) in a function declaration, and this function declaration automatically becomes a function template.

Press + to interact
#include <concepts>
#include <iostream>
template <typename T>
requires std::integral<T>
T gcd(T a,T b) {
if( b == 0 ) return a;
else return gcd(b, a % b);
}
template<typename T>
T gcd1(T a,T b) requires std::integral<T> {
if( b == 0 ) return a;
else return gcd1(b, a % b);
}
template<std::integral T>
T gcd2(T a,T b) {
if( b == 0 ) return a;
else return gcd2(b, a % b);
}
std::integral auto gcd3(std::integral auto a,std::integral auto b) {
if( b == 0 ) return a;
else return gcd3(b, a % b);
}
auto gcd4(auto a,auto b) {
if( b == 0 ) return a;
return gcd4(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 << "gcd4(100, 10)= " << gcd4(100, 10) << '\n';
std::cout << '\n';
}

The definitions of the function templates gcd (line 4), gcd1 (line 11), and gcd2 (line 17) are the ones I already presented in section Four Ways to Use a Concept. gcd uses a requires clause, gcd1 a trailing requires clause, and gcd2 a constrained template parameter.

Now to something new. Function ...