templates

Variadic Templates or the Power of Three Dots

A variadic template is a template that can have an arbitrary number of template parameters. This feature may seem magical to you if you see it for the first time. So, let me demystify variadic templates.

 templates

You may wonder if my graphic showing the topics I write about includes template instantiation. The reason is simple. After my last post about “Template Instantiation“, one of my German readers (pseudonym Urfahraner Auge) commented. There is an essential difference between implicit and explicit instantiation of a template that I forgot to mention. He is right. The implicit instantiation of templates is lazy, but the explicit instantiation of templates is eager.

Lazy versus Eager Template Instantiation

Template instantiation is lazy. It will not be instantiated if you don’t need a member function of a class template. Only the member function declaration is available, but not its definition. This works so far that you can use an invalid code in a member function. Of course, the member function must not be called.

// numberImplicitExplicit.cpp

#include <cmath>
#include <string>

template <typename T>
struct Number {
	int absValue() {
        return std::abs(val);
    }
  T val{};
};

// template class Number<std::string>;           // (2)
// template int Number<std::string>::absValue(); // (3)

int main() {
  
    Number<std::string> numb;
    // numb.absValue();                         // (1)
  
}

 

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    If you call the member function numb.absValue() (line 1), you get what you may expect. A compile-time error message essentially says that the is no overload std::abs for std::string available. Here are the first two lines from the verbose error message:

    numberImplicitExplicit

    I have to explain template instantiation more precisely: The implicit instantiation of templates is lazy, but the explicit instantiation of templates is eager.

    When you enable line (2) (template class Number<std::string>) and explicitly instantiated the class template Number or you enable line (3) (template int Number<std::string>::absValue()) and explicitly instantiated the member function absValue for std::string, you get a compile-time error. This compile-time error is equivalent to the compiler error invoking the member function absValue in line (1) (numb.absValue()). Once more, here are the first two lines of the error messages after enabling line (2) or line (3).

    • Line (2) enabled

    numberImplicitExplicit2

    • Line (3) enabled

    numberImplicitExplicit3

    A Personal Note:

    I’m keen on getting comments about my posts. They help me to write about the content I want to hear. In particular, the German community is very engaged.

    Now, finally, to something completely different: variadic templates.

    Variadic Templates

     A variadic template is a template that can have an arbitrary number of template parameters. If you see it for the first time, this feature may seem magical to you.

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

     

    The ellipsis (...) makes Args or args a so-called parameter pack. Precisely, Args it 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.

    Variadic templates are often used in the Standard Template Library and the core language.

    template <typename... Types>                                              // (1)
    class tuple; 
    
    template <typename Callable, typename... Args >                           // (2)
    explicit thread(Callable&& f, Args&&... args);	
    
    template <typename Lockable1, typename Lockable2, typename... LockableN>  // (3)
    void lock(Lockable1& lock1, Lockable2& lock2, LockableN&... lockn);
    
    sizeof...(ParameterPack);                                                 // (4)
    

     

    All four examples from the C++11 standard use variadic templates. The first three are part of the Standard Template Library. Let’s see what I can deduce from the declarations.

    1. std::tuple accepts an arbitrary number of different types.
    2. std::thread allows it to invoke a callable with an arbitrary number of arguments. The argument can have different types. You can invoke a callable, such as a function, function object, or lambda expression. The function std::thread takes its callable and its arguments by universal reference. If you need more detail: I already wrote about template argument deduction and universal references in my post “Template Arguments“. 
    3. std::lock It can lock an arbitrary number of lockable types in an atomic step. Locking one lockable type in an atomic step is trivial. Consequently, std::lock requires at least two arguments. Lockable is named requirement. Types supporting Lockable must have the member functions lock, unlock, and try_lock.
    4. The sizeof ... – operator returns the number of elements in the ParameterPack.

    The sizeof...-operator seems special because the ParameterPack is used in the core language. Let me write a few words about it.

    sizeof...-Operator

    Thanks to the sizeof …-operator can be used to determine how many elements a parameter pack contains directly. The elements are not evaluated.

    // printSize.cpp
    
    #include <iostream>
    
    using namespace std::literals;
    
    template <typename ... Args>
    void printSize(Args&& ... args){
        std::cout << sizeof...(Args) << ' ';              // (1)
        std::cout << sizeof...(args) << '\n';             // (2)
    }
    
    int main() {
    
        std::cout << '\n';
    
        printSize();                                       // (3)
        printSize("C string", "C++ string"s, 2011, true);  // (4)
    
        std::cout << '\n';
    
    }
    

     

    The sizeof..-operator allows it to determine the size of the template parameter pack (1) and the function parameter pack (2) at compile time. I apply it to an empty parameter pack (3) and a parameter pack containing four elements. The first element is a C-string and the second a C++ string. To use the C++-string literal, I have to include the namespace std::literals (5). C++14 supports C++ string literals.

    printSize

    What’s next?

    In my next post, I dive deeper into variadic templates and introduce the functional pattern to evaluate a variadic template. Additionally, I  present the perfect factory function and jump from C++11 to C++17: fold expression in C++17.

    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, 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, Philipp Lenk, Hobsbawm, and Charles-Jianye Chen.

    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

    Seminars

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

    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++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

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