Search code examples
c++variadic-templatesvariadic-functionsvariadic

Variadic C++ Templates Termination After Unpack?


I'm trying to use C++ variadic templates to unpack a list of arguments of variable type, how would I remove the "T" object in the following artificial example:

struct Test
{
    template <typename T, typename... Args>
    void foo(T t, int i, Args... args) { foo(t, args...); }

    template <typename T, typename... Args>
    void foo(T t, double d, Args... args) { foo(t, args...); }

    template <typename T>
    void foo(T t) { }
};

struct DummyObject { };

and then executed like this:

DummyObject dummy;
Test test;
test.foo(dummy, 4, 5.0, 6, 7.0, 8.0, 9);

I'd like to remove the need to pass in the "dummy" object at all, I just can't figure out what the final "foo" function should look like in this case.


Solution

  • Let me flesh out your sample slightly:

    struct Test
    {
        template <typename T, typename... Args>
        void foo(T t, int i, Args... args) { doIThing(i); foo(t, args...); }
    
        template <typename T, typename... Args>
        void foo(T t, double d, Args... args) { doDThing(d);  foo(t, args...); }
    
        template <typename T>
        void foo(T t) { }
    };
    

    So there's the two functions that do actual work: doIThing and doDThing. You got it 99% right, just... remove T.

    struct Test
    {
        template <typename... Args>
        void foo(int i, Args... args) { doIThing(i); foo(args...); }
    
        template <typename... Args>
        void foo(double d, Args... args) { doDThing(d);  foo(args...); }
    
        void foo() { }
    };
    

    Running here: http://coliru.stacked-crooked.com/a/b35ac716cf2960b3