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.
Here is a short reminder.
A variadic template is a template that can have an arbitrary number of template parameters.
The ellipsis (
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
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<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.
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.
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.
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
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, Kris Kafka, 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, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, 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, moon, and Philipp Lenk.
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|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,