Search⌘ K

Abbreviated Function Templates

Explore how C++20 introduces abbreviated function templates that allow function declarations with auto or concept constraints to become function templates automatically. Understand the syntax, usage of concepts like std::integral, and how overloading works with abbreviated templates to write clearer and type-safe code.

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.

C++
#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 template gcd3 has the concept std::integral as a type parameter and becomes, therefore, ...