More about Variadic Templates ...

More about Variadic Templates ...

This post is a cross-post from www.ModernesCpp.com.

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 with an analysis of 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 is 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 is 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 or use fold expression or constexpr if in C++17. I will write about fold expressions and constexpr if in future posts.?Said that 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.

  • Perform an operation 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 for 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 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.

No alt text provided for this image

Now, to the interesting part: What happens under the hood. Let 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:

No alt text provided for this image

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 I introduce variadic templates I ask my participants: Whom of you ever used an ellipse? Half of my participants answer never. I answer 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, therefore, 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 is not equal to `\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.

No alt text provided for this image

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

  • Four arguments:

No alt text provided for this image

  • Thee arguments:

No alt text provided for this image

  • Two arguments:

No alt text provided for this image

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 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, Marko, G Prvulovic, Reinhold Dr?ge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschl?ger, Red Trip, Alexander Schwarz, Tornike Porchxidze, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Satish Vangipuram, Michael Dunsky, and Dimitrov Tsvetomir.

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, and Said Mert Turkal.

My special thanks to Embarcadero

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++

?

?

要查看或添加评论,请登录

社区洞察

其他会员也浏览了