Variadic Functions

An introduction to variadic functions, which allow us to pass a variable quantity of arguments

Ryan McCombe
Updated

Often, we'll want to implement a function that can accept any number of arguments. Our reasons for needing to do this broadly fall into two categories:

API Design / Optimising Developer Experience

Sometimes, the most intuitive API we can provide for a function is a highly flexible parameter list. For example, if we're creating a logging library, the friendliest way to let ourselves or other developers use it is to accept everything they want to log as arguments:

Log(A, B, C);

But we don't know in advance how many things a consumer is going to want to log in a single function call. We could pick an arbitrary limit like 10 and throw an error if someone goes over that. But, as we'll soon learn, such a restriction is not necessary.

Forwarding Arguments to an Unknown Function

Often, we'll need to write a function that accepts arguments that ultimately need to be passed on to another function. And, at the time we're writing our code, we don't know what that function will be, or how many arguments it will accept.

We've seen examples of this in the standard library, such as the std::make_unique() and std::make_shared() functions to create smart pointers and the emplace() methods that exist on various containers.

These functions accept a list of arguments that will be passed along to a constructor. But they don't know which constructor they're forwarding to, or even the type they're constructing. That depends on a template parameter. As such, these types of functions need to have a highly flexible parameter list.

Parameter Packs

The key mechanism that lets modern C++ functions accept a variable number of parameters is a parameter pack.

A parameter pack is a collection of zero or more parameters. There are two types:

  • Template parameter packs are collections of template parameters
  • Function parameter packs are collections of function parameters

We define a parameter pack using ... syntax. The following example shows a function template that uses both a template parameter pack and a function parameter pack.

In this case, we've called our template parameter pack Types and our function parameter pack Arguments, but we're free to use any name, subject to the usual naming rules.

template <typename... Types>
void MyFunction(Types... Arguments){
  // ...
}

A function that uses a parameter pack is called a variadic function, and can be called with a variable number of arguments:

template <typename... Types>
void MyFunction(Types... Arguments){
  std::cout << "Hello!\n";
}

int main(){
  MyFunction();
  MyFunction(3);
  MyFunction(42, false, "Hello");
}
Hello!
Hello!
Hello!

References within Parameter Packs

It's also possible to capture arguments by reference, using the & operator in the usual way:

template <typename... Types>
void Function(Types&... Arguments){
  // ...
}

And by const references:

template <typename... Types>
void Function(const Types&... Arguments){
  // ...
}

We can also use &&, but it doesn't necessarily denote an rvalue reference. When suffixed to a deduced type (such as a template or auto) the && syntax denotes a forwarding reference, which is sometimes also called a universal reference.

For now, we can just note that using && with our template type allows our function to work with both lvalue and rvalue references:

template <typename... Types>
void Function(Types&&... Arguments){
  // ...
}

int main(){
  int A{1};
  Function(A, 2);
}

We covered lvalues and rvalues in our earlier lesson on , and we have a dedicated lesson later in the course that covers forwarding in more detail.

The sizeof... operator

A variation of the sizeof operator is available to return the number of parameters in a parameter pack. It is the sizeof... operator:

template <typename... Types>
void Function(Types... Arguments){
  std::cout
    << "Received "
    << sizeof...(Arguments)
    << " Arguments";
}

int main(){ Function(42, "Hello", true); }
Received 3 Arguments

Unpacking Parameter Packs

Once we have a parameter pack, we will often need to "expand" or "unpack" it to its constituent parameters. Typically, this is done to get a series of values to forward to some other function, as individual arguments.

To do this, we also rely on the ... syntax. In the following example, we expand our parameter pack to provide arguments to a std::tuple constructor:

template <typename... Types>
void MyFunction(Types... Arguments){
  std::tuple Tuple{Arguments...};
}

We covered tuples in more detail in an .

Notably, std::tuple is a template class. In the previous example, we used Class Template Argument Deduction (CTAD) to let the compiler figure out the template parameters based on our initialization values.

But we can unpack template parameters in the same way, should we ever need or want to:

template <typename... Types>
void MyFunction(Types... Arguments) {
  std::tuple<Types...> Tuple { Arguments... };
}

While expanding our parameter pack, we can use any expression that includes the name of our pack. Each argument of our parameter pack will be passed into that expression in turn, and we then forward the value that the expression returns.

In the following example, we calculate what each argument will be if we multiply it by 2, and we forward those values instead of our original parameter pack values.

Typically, tasks like this will require the introduction of additional brackets to control the order of operations:

#include <iostream>
#include <tuple>

template <typename... Types>
void Function(Types... Arguments){
  std::tuple Tuple{(Arguments * 2)...};

  std::cout << "First Object in Tuple: "
    << std::get<0>(Tuple);
}

int main(){ Function(2, 5, 10); }
First Object in Tuple: 4

In the following example, we pass each argument to a function and forward the return values of those function calls to our tuple constructor. This unlocks a lot of possibilities, but below, our intermediate function is simply logging the value and then returning it:

#include <iostream>
#include <tuple>

template <typename T>
T Log(T Object){
  std::cout << Object << '\n';
  return Object;
}

template <typename... Types>
void Function(Types... Arguments){
  std::tuple Tuple{Log(Arguments)...};

  std::cout << "First Object in Tuple: "
    << std::get<0>(Tuple);
}

int main(){ Function(2, 5, 10); }
2
5
10
First Object in Tuple: 2

Compile Time Checks

When creating variadic functions, quite often the logic we write will be invalid if the size of our argument list is 0. This is true of our previous tuple examples - if Function() were ever called with 0 arguments, our code would fail to compile.

A simple if statement does not solve this, as if statements are evaluated at run time. The compiler doesn't know what will happen at run time, so it requires all branches of our code to be syntactically valid.

As such, we'll often be using if constexpr statements in our variadic functions. These blocks remove code entirely from our application, unless some condition we specify is true at compile time.

In the following example, we only construct the tuple if our function was called with 1 or more arguments:

#include <iostream>
#include <tuple>

template <typename... Types>
void Function(Types... Arguments){
  if constexpr (sizeof...(Arguments) > 0) {
    std::tuple Tuple{Arguments...};

    std::cout << "First Argument: " << std::get<0>(Tuple);
  } else {
    std::cout << "\nParameter pack is empty!";
  }
}

int main(){
  Function(42, false, "Hello");
  Function();
}
First Argument: 42
Parameter pack is empty!

The overload resolution and SFINAE rules that we covered previously apply to variadic functions and templates, too. The following example implements the same behaviour using overloaded functions:

#include <iostream>
#include <tuple>

void Function() {
  std::cout << "\nParameter pack is empty!";
}

template <typename... Types>
void Function(Types... Arguments) {
  std::tuple Tuple{Arguments...};
  std::cout << "First Argument: " << std::get<0>(Tuple);
}

int main() {
  // Only the template overload matches
  Function(42, false, "Hello");
  
  // Both the plain function and template matches
  // but the non-template wins overload resolution
  Function();
}
First Argument: 42
Parameter pack is empty!

Ensuring Variadic Function Calls Have Arguments

Parameter packs can have any number of arguments, and as we've seen, that number can include 0

In most scenarios where we're creating variadic functions, calling them with zero arguments doesn't make sense for our use case.

We can ensure our template function is only callable with 1 or more arguments by pulling the first parameter out of the pack, and using it like we would a regular parameter.

In the following example, we've separated our first parameter, both in the template parameter list (where we've called the first parameter T1) and in the function parameter list (where we've called the first parameter Arg1):

#include <iostream>
#include <tuple>

template <typename T1, typename... Types>
void Function(T1 Arg1, Types... Arguments){
  std::tuple Tuple{Arg1, Arguments...};
}

int main(){
  Function(42, false, "Hello");
  Function();
}

Now, our function has one required argument, followed by a parameter pack of any number (including zero) of additional arguments.

The previous example now generates a compilation error, as Function() doesn't provide the required Arg1 value:

'Function': no matching overloaded function found

Implementing Variadic Logic

Sometimes, our variadic functions have requirements that are a little more complex than simply forwarding their parameters to some other function. Instead, our function might need to directly implement logic that works with any number of parameters.

We'll see more examples of how to accomplish this soon, but one option involves using the recursive techniques we covered .

Most commonly, this means handling the first parameter in the pack, and then recursively re-calling the function with the remaining parameters.

This has the effect that every subsequent recursive call has one fewer argument than the previous. Eventually, there will be no parameters left, meaning the sizeof... our parameter pack will be 0. At that point, we can stop the recursion:

#include <iostream>

template <typename T1, typename... Types>
void Log(T1 First, Types... Others) {
  std::cout << "Logging: " << First << '\n';
  
  if constexpr (sizeof...(Others) == 0) {  
    // Base Case - Stop Recursion
    std::cout << "Done!";
  } else {
    // Recursive Case
    std::cout << sizeof...(Others)
      << " Parameter(s) Remaining\n\n";
    Log(Others...);
  }
}

int main() {
  Log(42, 9.8, "Hello");
}
Logging: 42
2 Parameter(s) Remaining

Logging: 9.8
1 Parameter(s) Remaining

Logging: Hello
Done!

The combination of parameter packs and recursion can be overwhelming, so don't worry if the flow of the previous program is difficult to follow. If it doesn't make sense, it may be helpful to step through it in a debugger.

Alternatively, the following program implements the same idea, but in a slightly different way:

#include <iostream>

template <typename T1, typename... Types>
void Log(T1 First, Types... Others){
  std::cout << "Logging: " << First << '\n';
  if constexpr (sizeof...(Others) > 0) {
    std::cout << sizeof...(Others)
      << " Parameter(s) Remaining\n\n";
    Log(Others...);
  }
}

int main(){
  Log(42, 9.8, "Hello");
}
Logging: 42
2 Parameter(s) Remaining

Logging: 9.8
1 Parameter(s) Remaining

Logging: Hello

Another variation of this recursive behavior is shown below. In this example, once the size of our argument list reaches 1, overload resolution uses a different, non-recursive Log function:

#include <iostream>

template <typename T>
void Log(T Object){
  std::cout << "Finally: " << Object;
}

template <typename T1, typename... Types>
void Log(T1 First, Types... Others){
  std::cout << "Logging: " << First << '\n';
  Log(Others...);
}

int main(){
  Log(42, 9.8, "Hello");
}
Logging: 42
Logging: 9.8
Finally: Hello

Is this Really Recursion?

Whilst this logic is recursive, it doesn't technically fit the typical understanding of recursion - that is, "a function calling itself". We're not recursively calling the same function in these C++ examples. Rather, we're recursively instantiating a function template to create different functions.

Each instantiation of a Log template uses a different argument list than the previous. In our Log(42, 9.8, true) example, our recursive logic:

  • Creates a function using a Log<int, double, bool> template instantiation, and calls that function
  • That function uses a Log<double, bool> template instantiation, and calls the created function
  • Finally, that function uses a Log<bool> template instantiation, and calls the created function

The Types parameter pack is progressively getting shorter, until it eventually has a size of only 1 - a single bool. At that point, overload resolution switches to using the topLog template, which explicitly uses a single parameter rather than a variadic parameter pack.

This top template creates a non-recursive function, so it marks the end of the process.

Preview: Fold Expressions

Using these template-based recursion techniques can result in the compiler generating a lot of functions. This is particularly true if we're using our variadic templates heavily throughout our project, with a wide variety of argument types.

The raw volume of code involved in a project can have performance implications in many environments. If we can solve our specific problem without using variadic functions at all, it's often worth avoiding them.

When we do need to use variadic functions, C++17 introduced fold expressions, which can help us mitigate some of the problems. These provide us with more succinct options to implement simple recursive behaviors that cover most use cases, without the overhead of full-fledged recursive templates.

We can get very close to our previous behavior with a one-line fold expression:

#include <iostream>

template <typename... Types>
void Fold(Types... Args){
  (std::cout << ... << Args);
}

int main(){
  Fold("Hello ", "World", '!');
}
Hello World!

We explain how this works and cover fold expressions in detail in our next lesson.

Summary

In this lesson, we covered variadic functions, learning how they enable functions to accept any number of arguments through parameter packs. The key topics we learned include:

  • Variadic functions allow for a variable number of arguments, which is useful for API design and argument forwarding.
  • Parameter packs can be divided into template parameter packs and function parameter packs, both defined using the ellipsis syntax.
  • Arguments within parameter packs can be captured by value, by reference, by const reference, and as forwarding references to support both lvalue and rvalue references.
  • The sizeof... operator helps determine the number of arguments in a parameter pack, useful for conditional logic and compile-time evaluations.
  • Unpacking parameter packs enables forwarding arguments to other functions or constructors, such as when initializing a std::tuple.
  • Compile-time conditionals with if constexpr and techniques like SFINAE ensure code validity even when argument lists vary in size, including zero arguments.
  • Ensuring variadic function calls have at least one argument can be achieved by separating the first parameter from the rest of the pack.
  • Implementing variadic logic often involves recursive template function calls, where each call handles a subset of the parameter pack until all arguments are processed.
  • Fold expressions introduced in C++17 offer a concise and efficient way to apply an operation to each element in a parameter pack
Next Lesson
Lesson 73 of 128

Fold Expression

An introduction to C++17 fold expressions, which allow us to work more efficiently with parameter packs

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Passing Parameter Packs by Value or Reference
When should I pass the parameters in a parameter pack by value, reference, const reference, or forwarding reference?
Recursion vs Fold Expressions
When should I use fold expressions over recursive variadic function calls?
Capturing Lvalues and Rvalues in Variadic Functions
How can I write a variadic function that can accept both lvalue and rvalue arguments?
Zero Argument Variadic Functions
What happens if I call a variadic function with no arguments?
Performance Considerations with Variadic Functions
Are there any performance implications to using variadic functions?
Why use parameter packs instead of just va_args?
I can already write variadic functions in C++ using va_args. Why would I use parameter packs instead?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant