Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive variadic function template

I want to write a class method that takes a template parameter pack, but zero arguments, and "iterate" over the types:

struct Bar {
    template <typename T, typename... Ts>
    void foo() {
        // something with T that involves Bar's members
        foo<Ts...>();
    }
};

What is the preferred way to implement this?

like image 331
Barry Avatar asked Mar 05 '15 14:03

Barry


People also ask

What is Variadic template in C++?

Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration.

What is the use of Variadic templates?

With the variadic templates feature, you can define class or function templates that have any number (including zero) of parameters. To achieve this goal, this feature introduces a kind of parameter called parameter pack to represent a list of zero or more parameters for templates.

What is parameter pack in c++?

Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.


1 Answers

You may use the following:

struct Bar {
    template <typename... Ts>
    void foo() {
        int dummy[] = {0 /*Manage case where Ts is empty*/,
                       (bar<Ts>(), void() /* To avoid overload `operator,` */, 0)...};
        (void) dummy; // suppress warning for unused variable.
    }

    template <typename T>
    void bar()
    {
        // something with T that involves Bar's members
    }

};

In C++17, it can be simplified with Folding expression:

struct Bar {
    template <typename... Ts>
    void foo() {
        (static_cast<void>(bar<Ts>()), ...);
    }

    template <typename T>
    void bar()
    {
        // something with T that involves Bar's members
    }

};
like image 63
Jarod42 Avatar answered Oct 21 '22 08:10

Jarod42