...

/

Variadic Function Templates

Variadic Function Templates

Gain an in-depth understanding of variadic function templates, which are template functions with a variable number of arguments.

Understanding the use of ellipsis (...)

Variadic function templates are template functions with a variable number of arguments. They borrow the use of the ellipsis (...) for specifying a pack of arguments, which can have different syntax depending on its nature.

To understand the fundamentals for variadic function templates, let’s start with an example that rewrites the previous min function:

Press + to interact
template <typename T>
T min(T a, T b)
{
return a < b ? a : b;
}
template <typename T, typename... Args>
T min(T a, Args... args)
{
return min(a, min(args...));
}
int main() {
std::cout << "min(42.0, 7.5)=" << min(42.0, 7.5)<< '\n';
std::cout << "min(1,5,3,-4,9)=" << min(1, 5, 3, -4, 9) << '\n';
}

What we have here are two overloads for the min function. The first is a function template with two parameters that returns the smallest of the two arguments. The second is a function template with a variable number of arguments that recursively calls itself with an expansion of the parameters pack. Although variadic function template implementations look like using some sort ...