Search code examples
c++templatesvariadic-templates

C++ variadic templates with repeating types


Is it possible to write variadic templates or fold expressions where the function signature can be something like

void f(int, string, int, string, ...)

That style is very popular and user-friendly in python, but I couldn't get it to work in C++. In particular I would use it to feed a plotting function with data followed by a label for example.

edit: to expand, I would like to call the function like this:

f(5, "first number");
f(5, "first number", 6, "second number");

and with 4, 6 or ... 2*n parameters.


Solution

  • You can write a variadic function like this:

    template<typename ...Ts>
    void f(int data, string const &label, Ts&&... rest)
    {
      process(data, label);
      f(std::forward<Ts>(rest...));
    }
    

    with a base case:

    void f() {}
    

    to terminate the recursion.

    Now only calls of the form:

    f(1, "hi");           // ok
    f(1, "hi", 2, "bye"); // ok
    // etc
    

    will compile, whereas:

    f(1);          // error
    f("hi");       // error
    f(1, "hi", 2); // error
    

    will not.