~/okanakyuz
← all posts

Variadic Template

Variadic templates in C++: parameter packs, recursion with an empty base case, sizeof... and C++17 fold expressions.

9 March 2020updated 25 November 20261 min read

Nested boxes as a picture of recursion

In C++, a template can take any number of template arguments.

template<typename ... Param>

Here Param is not one strict type but a parameter pack: zero or more types.

You may use it with other type names too:

template<typename T, typename ... Param>
void Display(T a, Param ... args){}

And of course, you may create a function that calls itself recursively. But it needs its empty version too, to stop the recursion.

#include <iostream>
#include <utility>

void Display(){
    std::cout <<  std::endl;
}

template<typename T, typename ... Param>
void Display(T && a, Param && ... args){
    std::cout << a << ":" << sizeof... (args) << "\t";

    Display(std::forward<Param>(args) ...);
}

int main()
{
    Display(9,2,1,3,1,2,1.1,"c");
}

std::forward is used so the arguments keep their value category and a move constructor can be used when possible. See Perfect Forwarding with Template.

sizeof... is an operator that gives the number of elements in a parameter pack. It is evaluated at compile time.

Update (2026): Since C++17 you often don’t need the recursion. A fold expression expands the pack in one line:

template<typename ... Param>
void Display(Param && ... args){
    ((std::cout << args << "\t"), ...);
    std::cout << std::endl;
}

With C++20 abbreviated function templates you can even write it as void Display(const auto& ... args).