• Home
  • /
  • Blog
  • /
  • More about Variadic Templates …

August 13, 2021

There is a lot of power in the strange-looking three dots that are heavily used in the Standard Template Library. Today, I visualize the expansion of the three dots and show a few use cases.


Let me start this post by analyzing the pack expansion in variadic templates.

Pack Expansion

Here is a short reminder.

A variadic template is a template that can have an arbitrary number of template parameters.

template <typename ... Args>
void variadicTemplate(Args ... args) { 
    . . . . // four dots


The ellipsis (...) makes Args or args a so-called parameter pack. Precisely, Args is a template parameter pack and args a function parameter pack. Two operations are possible with parameter packs. They can be packed and unpacked. If the ellipse is to the left of Args, the parameter pack will be packed; if it is to the right of Args, it will be unpacked. Because of the function template argument deduction, the compiler can derive the template arguments.

Before I write about the pack expansion, I have to make a short disclaimer. Usually, you don’t apply pack expansion directly. You use variadic templates doing it automatically, using fold expression, or constexpr if in C++17. I will write about fold expressions and constexpr if in future posts. Visualizing pack expansions helps a lot for a better understanding of variadic templates and fold expressions.

The usage of parameter packs obeys a typical pattern for class templates.

  • Operate on the first element of the parameter pack and recursively invoke the operation on the remaining elements. This step reduces the parameter pack successively by its first element.
  • The recursion ends after a finite number of steps.
  • The boundary condition is typically a fully specialized template.

Thanks to this functional pattern for processing lists, you can calculate the product of numbers at compile time. In Lisp, you call the head of the list car, and the rest cdr. In Haskell, you call it head and tail.

// multVariadicTemplates.cpp

#include <iostream>

template<int ...>                                                 // (1)
struct Mult;

template<>                                                        // (2)
struct Mult<> {
    static const int value = 1;

template<int i, int ... tail>                                     // (3)
struct Mult<i, tail ...> {
    static const int value = i * Mult<tail ...>::value;

int main(){

    std::cout << '\n';

    std::cout << "Mult<10>::value: " << Mult<10>::value << '\n';  // (4)
    std::cout << "Mult<10,10,10>::value: " << Mult<10, 10, 10>::value << '\n';
    std::cout << "Mult<1,2,3,4,5>::value: " << Mult<1, 2, 3, 4, 5>::value << '\n';

    std::cout << '\n';



The class template Mult consists of a primary template and two specializations. Since the primary template (1) is not needed, a declaration is sufficient in this case: template<int ...> struct Mult. The specializations of the class template exist for no element (2) and at least one element (3). If Mult<10,10,10>::value is called, the last template is used by successively calling the first element with the rest of the parameter pack so that the value expands to the product 10*10*10. In the final recursion, the parameter pack contains no elements, and the boundary condition comes into action: template<> struct Mult<> (1). This returns the result of Mult<10,10,10>::value= 10*10*10*1 at compile time.


Now, to the exciting part: What happens under the hood? Let’s have a closer look at the call Mult<10,10,10>::value. This call triggers no recursion but a recursive instantiation. Here are the essential parts from C++ Insights:

multInstantiationThe compiler generates full specializations for three (Mult<10, 10, 10>) and two arguments (Mult<10, 10>). You may ask yourself: Where are the instantiations for one (Mult<10>) and no argument (Mult<>). Mult<10> was already requested in (4) and Mult<> (1) is the boundary condition.

Let me continue with an anecdote. When introducing variadic templates, I ask my participants: Who of you ever used an ellipse? Half of my participants answer never. I answered them that I don’t believe them and they may be heard from the printf family.

A Type-Safe printf Function

Of course, you know the C function printf: int printf( const char* format, ... );. printf is a function that can get an arbitrary number of arguments. Its power is based on the macro va_arg and is not type-safe. Let’s implement a simplified printf function using variadic templates. This function is the hello world of variadic templates.

// myPrintf.cpp

#include <iostream>
void myPrintf(const char* format){                           // (3)
    std::cout << format;
template<typename T, typename ... Args>
void myPrintf(const char* format, T value, Args ... args){   // (4)
    for ( ; *format != '\0'; format++ ) {                    // (5)
        if ( *format == '%' ) {                              // (6) 
           std::cout << value;
           myPrintf(format + 1, args ... );                  // (7)
        std::cout << *format;                                // (8)
int main(){
    myPrintf("\n");                                          // (1)
    myPrintf("% world% %\n", "Hello", '!', 2011);            // (2)


How does the code work? If myPrintf is invoked without a format string (1), (3) is used in the case. (2) uses the function template. The function templates loops (5) as long as the format symbol does not equal `\0`. If the format symbol is not equal to `\0 , two control flows are possible. First, if the format starts with ‘%‘  (6), the first argument value is displayed, and myPrintf is once more invoked, but this time with a new format symbol and an argument less (7). Second, if the format string does not start with '%‘, the format symbol is just displayed (line 8). The function myPrintf (3) is the boundary condition for the recursive calls.

The output of the program is as expected.


As before, C++ Insights helps much to get more insight into the template instantiation process. Here are the three instantiations caused by myPrintf("% world% %\n", "Hello", '!', 2011);:

  • Four arguments:



  • Thee arguments:



  • Two arguments:


Short Two Weeks Break

Due to vacation and probably limited connectivity, I will not publish a post in the next two weeks. If you want to publish a guest post, please let me know.

What’s Next?

In my next post, I will use variadic templates to implement the C++ idiom for a fully generic factory. One implementation of this life-saving C++ idiom is std::make_unique.




Leave a Reply

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Related Posts