Variadic Templates in C++11 (Part 1 of 2)

This week we are continuing with the C++11 saga, moving on to a new feature called “Variadic Templates”.

Inspired by the concept of Variadic Functions in C, the idea behind Variadic Templates is to allow a template to be instanciated with any number of arguments.

In this article I’ll cover the new syntax and present a simple example that declares a function that uses a Variadic Template that prints the number of arguments it was intantiated with.

Previous parts of this saga included an overview of new iterators and lambda expressions as well as Move Semantics, which was treated in two parts: Part 1 and Part 2.

Let’s get started!

First of all, C++11 had to extend the C++ syntax for templates in order to support Variadic Templates. The new syntax allows annotating a parameter with an ellipsis (…) to denotate that we may expect receive zero or more parameters in the given place.

This means that the following declaration is now valid C++:

template <class... T>
void f()
{
}

f is a function that can be expanded with zero or more template parameters.

Now that we know how to declare a Variadic Template, let’s write a simple program that prints the number of arguments the function f template has been expanded with.

#include <iostream>
using std::cout;
using std::endl;

template <class... T>
size_t f()
{
    return sizeof...(T);
}

int main(int argc, char* argv[])
{
    cout << "sizeof f<int>" << f<int>() << "\n";
    cout << "sizeof f<int, float>" << f<int, float>() << "\n";
    cout << "sizeof f<int, float, char>" << f<int, float, char>() << endl;
    return 0;
}

Compiling this program with clang and running it produces the following output:

sizeof f<int>: 1
sizeof f<int, float>: 2
sizeof f<int, float, char>: 3

Here, each line of the output corresponds to the number of parameters the function template was instantiated with. As you probably noticed, the new sizeof… takes the packed template arguments and returns their count. If we just called f without instantiating its template, the number of arguments printed would be 0.

Now, you might be wondering what Variadic Templates might be used for. In next week’s article I will show you how to write a typesafe printf-like function in C++11 style. Stay tuned!