liveBook · Manning

Variadic template

As explained in 100 C++ Mistakes and How to Avoid Them

A variadic template is a C++ template that accepts a variable number of template arguments or function arguments.

Mistake 18: replacing a variable-length parameter list with a vector adds storage and loop management where a variadic template can accept arguments directly. section 4.1

Define a base case for one argument, then a recursive case containing the remaining parameter pack. The compiler repeatedly expands the calls until only the base case remains. C++17 fold expressions can condense the recursive implementation. section 4.1

Listing 4.1 Using a vector to implement a variadic parameter list
template <typename T>
T sum(T initial, const std::vector<T>& vals) {            #1
    T sum = initial;
    for (int i = 0; i < vals.size(); ++i)
        sum += vals[i];
    return sum;
}
 
int main() {
    std::vector<int> intvalues;                           #2
    for (int i = 1; i < 10; ++i)                          #3
        intvalues.push_back(i);
    std::cout << sum(0, intvalues) << '\n';               #4
    std::vector<double> doublevalues;
    for (int i = 1; i < 4; ++i)
        doublevalues.push_back(i);
    std::cout << sum(5.0, doublevalues) << '\n';
    return 0;
}

Compare the vector-based sum with the templatized variadic version and its C++17 fold-expression alternative. section 4.1

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains base and recursive cases, compiler expansion, and a C++17 fold-expression alternative.
Examples
Contrasts summing values from a vector with direct calls accepting two, three, or four arguments.
What you can do after
Build variable-length sum functions using a base case, recursive parameter pack, or C++17 fold expression.
How it connects
Connects variadic templates with templates, parameter packs, recursive functions, and fold expressions.

Also explained in

Compare how 2 books explain variadic template →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.