Variadic Templates or the Power of Three Dots

Contents[Show]

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 the first time. So, let me demystify variadic templates.

 templates

You may wonder that 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) made a comment. There is an important 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. Meaning, if you don't need a member function of a class template it will not be instantiated. Only the declaration of the member function is available, but not its definition. This works so far that you can use 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)
  
}

 

If you call the member function numb.absValue() (line 1), you get what you may expect. A compile-time error message essentially saying 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 you 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. This feature may seem magical to you if you see it the first time.

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 to the right of  Args, it is 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 also in 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. A callable is something you can invoke such as a function, a function object, or a 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 allows it to 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 to be 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 directly determine how many elements a parameter pack contains. 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, 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, Michael Dunsky, Dimitrov Tsvetomir, Leo Goodstadt, Eduardo Velasquez, John Wiederhirn, and Yacob Cohen-Arazi.

 

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 CBUIDER STUDIO FINAL ICONS 1024 Small

 

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++,

RainerGrimmSmall

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 3867

Yesterday 8323

Week 36747

Month 110157

All 7172447

Currently are 183 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments