Search code examples
c++templatesvariadic-functionsvariadic

How to use variadic templates to wrap a variable number of function arguments?


I want to take a variable number of function arguments, and in the function itself, wrap each function argument using a template wrapper class and pass these wrapper classes as arguments to another function.

Say if I have a template class that simply wraps a variable.

template<class T>
class Wrapper
{
public:
    Wrapper(T t) : t_(t)
.
.
    {}
private:
    T t_;
}

And I have a function f that calls function g, passing in Wrapper classes for each argument of f to g.

template <typename T1, typename T2, typename T3>
void f(T1 a, T2 b, T3 c)
{
    g(Wrapper<T1>(a), Wrapper<T2>(b), Wrapper<T3>(c));
}

Function g is not important here, but could be for example, a sequence of overloaded functions, each with a different number and type of Wrapper classes as its parameters.

Is there a way to use variadic templates to call template method f with a variable number of arguments, passing in the same number of arguments but instead with their wrapper classes into function g?

Any help much appreciated, Tony


Solution

  • The technical term is parameter packs.

    And it should as "easy" as

    template<typename... T>
    void f(T... args)
    {
        g(Wrapper<T>(args)...);
    }
    

    Of course, it requires you to have the proper g function.