ArticleslgStudy

computer science

Variadic template

Variadic template is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Variadic template rather than just read about it. In short: In computer programming, variadic templates or variation generics are templates that take a variable number of type parameters. They exist in several programming languages and are used for the creation of type-safe generics with a variable number of types.

Key takeaways

  • Variadic template belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Variadic template to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Variadic template from memory before moving on to harder problems.

Reference excerpt

In computer programming, variadic templates or variation generics are templates that take a variable number of type parameters. They exist in several programming languages and are used for the creation of type-safe generics with a variable number of types. They are somewhat similar in nature to variadic functions or variadic macros. Variadic templates are supported by C++ (since the C++11 standard), and the D programming language. While other languages, such as Java or C# offer support for type-safe variadic functions, they do not offer the variadic generics support like that of C++ and D.

C++ Prior to the introduction of variadic templates to C++, variadic functions could only be implemented using va_list or variadic macros from C, which lack type safety. The variadic template feature of C++ was designed by Douglas Gregor and Jaakko Järvi and was later standardized in C++11. Prior to C++11, templates (classes and functions) could only take a fixed number of arguments, which had to be specified when a template was first declared. C++11 allows template definitions to take an arbitrary number of arguments of any type. Thus, the only way to get type-safe variadic functions is thus through variadic templates over functions, which are type-heterogeneous; C++ lacks homogeneous variadic parameters like those of Java and C#. Consider this Tuple<Ts...> class, similar to the standard library's std::tuple<Ts...>:

The above template class Tuple<Ts...> (representing a product type or tuple) will take any number of typenames as its template parameters. Here, an instance of the above template class is instantiated with three type arguments:

The number of arguments can be zero, so Tuple<> t; will also work. If the variadic template should only allow a positive number of arguments, then this definition can be used:

A common implementation of a tuple uses recursive decomposition like so:

Variadic templates may also apply to functions, thus not only providing a type-safe add-on to variadic functions (such as printf()), but also allowing a function called with printf-like syntax to process non-trivial objects.

The ellipsis (...) operator has two roles. When it occurs to the left of the name of a parameter, it declares a parameter pack. Using the parameter pack, the user can bind zero or more arguments to the variadic template parameters. Parameter packs can also be used for non-type parameters. By contrast, when the ellipsis operator occurs to the right of a template or function call argument, it unpacks the parameter packs into separate arguments, like the args... in the body of printf() below. In practice, the use of an ellipsis operator in the code causes the whole expression that precedes the ellipsis to be repeated for every subsequent argument unpacked from the argument pack, with the expressions separated by commas. The fixed-point combinator is often implemented using variadic template arguments (note that [](auto&&... args) is equivalent to []<template... Args>(Args&&... args)):

To constrain the parameter to be homogeneous and only of type T (similar to T... args) in Java, one can use the concept std::same_as<T, U> or std::convertible_to<From, To> (for types which may be intended to be convertible).

This can be further constrained to any specific type:

A proposal for "homogeneous variadic function parameters" proposes the Java-style form (T... args) directly; this was first proposed for C++20 in 2019, but abandoned, and then re-proposed for C++29 in 2026. Variadic parameter packs can be indexed with the indexing operator (for example T nth = args...[N - 1]); homogeneous packs must be the only function parameter pack, appear at the end, and cannot have C-style variadics.

The use of variadic templates is often recursive. The variadic parameters themselves are not readily available to the implementation of a function or class. Therefore, the typical mechanism for defining something like a C++11 variadic printf() replacement would be as follows:

This is a recursive template. Notice that the variadic template version of myPrintf() calls itself, or (in the event that args... is empty) calls the base case. There is no simple mechanism to iterate over the values of the variadic template. However, there are several ways to translate the argument pack into a single argument that can be evaluated separately for each parameter. Usually this will rely on function overloading, or — if the function can simply pick one argument at a time — using a dumb expansion marker:

which can be used as follows:

which will expand to something like:

The use of this "pass" function is necessary, since the expansion of the argument pack proceeds by separating the function call arguments by commas, which are not equivalent to the comma operator. Therefore, foo(args)...; will never work. Moreover, the solution above will only work when the return type of foo() is not void. Furthermore, the foo() calls will be executed in an unspecified order, because the order of evaluation of function arguments is undefined. To avoid the unspecified order, brace-enclosed initializer lists can be used, which guarantee strict left-to-right order of evaluation. An initializer list requires a non-void return type, but the comma operator can be used to yield 1 for each expansion element.

Instead of executing a function, a lambda expression may be specified and executed in place, which allows executing arbitrary sequences of statements in-place.

However, in this particular example, a lambda function is not necessary. A more ordinary expression can be used instead:

In C++17, these can be rewritten using fold expressions on the comma operator:

Another way is to use overloading with "termination versions" of functions. This is more universal, but requires a bit more code and more effort to create. One function receives one argument of some type and the argument pack, whereas the other receives neither. (If both had the same list of initial parameters, the call would be ambiguous, as a variadic parameter pack alone cannot disambiguate a call.) For example:

If args... contains at least one argument, it will redirect to the second version — a parameter pack can be empty, in which case it will simply redirect to the termination version, which will do nothing. Variadic templates can also be used in an exception specification, a base class list, or the initialization list of a constructor. For example, a class can specify the following:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Variadic template

Start with the simplest possible case. Write down what Variadic template claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Variadic template before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Variadic template ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Variadic template

In research
Variadic template appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Variadic template in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Variadic template is common in secondary-school and first-year university syllabi. It links to neighbouring topics Computer programming, so understanding it makes those chapters shorter.
In everyday life
Look for Variadic template outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Variadic template” →

How to study Variadic template in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Variadic template means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Variadic template out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Variadic template in simple terms?

In computer programming, variadic templates or variation generics are templates that take a variable number of type parameters. They exist in several programming languages and are used for the creation of type-safe generics with a variable number of types.

Why does Variadic template matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Variadic template?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Variadic template.

Tags

  • Computer programming

Keep exploring