Sobes.tech
Middle

Can a template in C++ have a variable number of arguments?

sobes.tech AI

Answer from AI

Yes, it can. Such templates are called variadic.

They use parameter packing and unpacking syntax:

  • Parameter pack: typename... Args or T... args. The ellipsis ... indicates that what follows is a template parameter pack or function argument pack.
  • Unpacking (Expansion): func(args...) or Template<Args...> within another template. The ellipsis ... here means unpacking the pack into individual elements.

An example could be an implementation of a print function with a variable number of arguments, similar to printf:

#include <iostream>

// Base case of recursion
void print() {
    std::cout << std::endl;
}

// Recursive template to process arguments
template <typename T, typename... Args>
void print(T value, Args... args) {
    std::cout << value << " ";
    print(args...); // Unpacking remaining arguments
}

int main() {
    print(1, "hello", 3.14);
    print("just one argument");
    return 0;
}

In this example, the print template recursively processes the arguments: the first argument value is processed, and the remaining arguments Args... args are passed recursively to the print(args...) function. The base case void print() stops the recursion when the arguments are exhausted.