More about Variadic Templates …
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.
Modernes C++ Mentoring
Do you want to stay informed: Subscribe.
- 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 ca
r, 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:
The 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 didn’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) return; } std::cout << *format; // (8) } } int main(){ myPrintf("\n"); // (1) myPrintf("% world% %\n", "Hello", '!', 2011); // (2) myPrintf("\n"); }
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 to gain 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
.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, Philipp Lenk, Charles-Jianye Chen, Keith Jeffery, Matt Godbolt, Honey Sukesan, bruce_lee_wayne, and Silviu Ardelean.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
My special thanks to Embarcadero | ![]() |
My special thanks to PVS-Studio | ![]() |
My special thanks to Tipi.build | ![]() |
My special thanks to Take Up Code | ![]() |
My special thanks to SHAVEDYAKS | ![]() |
Modernes C++ GmbH
Modernes C++ Mentoring (English)
Rainer Grimm
Yalovastraße 20
72108 Rottenburg
Mail: schulung@ModernesCpp.de
Mentoring: www.ModernesCpp.org
Leave a Reply
Want to join the discussion?Feel free to contribute!