MGH
MGH

Reputation: 475

Variadic template function overloading

I have a class with a variadic template member function (foo) like below. The idea is to skip all doubles in the parameter and allocate an object with user provided arguments.

template <class T>
class Var {
public:

    template <typename U, typename ...Args>
    int foo(int index, Args... args)
    {
        T* p = new U(args...);
        // save in an array at index 'index'
    }

    template <typename U, typename ...Args>
    int foo (double index, Args... args)
    {
        // do something with index and skip it
        return foo<U>(args...);
    }
};

class A {
public:
    A (int i, const char *p)
    {

    }
};

int main ()
{
    Var<A> var;

    var.foo<A>(1.0, 2, 3, "Okay");
}

Now this works, there are 2 problem.

Basically I want to pass the no. of ints to skip as class template parameter.

template <class T, int SKIP>
class Var {

And use SKIP to determine how many ints to skip.

Is it possible to do something like that?

Upvotes: 1

Views: 1901

Answers (2)

MGH
MGH

Reputation: 475

So this is what I conjured up taking hint from Novelocrat. Just pasting it hear for the records.

template <class T, int SKIP>
class FooHelper {
public:

    template <typename U, typename ...Args>
    static int foo_helper(int index, Args... args)
    {
        FooHelper<T, SKIP-1>::foo_helper<U>(args...);
        return 0;
    }
};

template <class T>
class FooHelper<T, 0> {
public:

    template <typename U, typename ...Args>
    static int foo_helper (Args... args)
    {
        auto p = new U(args...);
        return 0;
    }
};

template <class T, int SKIP>
class Var {
public:

    template <typename U, typename ...Args>
    int foo(Args ...args)
    {
        FooHelper<T, SKIP>::foo_helper<U>(args...);
        return 0;
    }
};

Upvotes: 1

Phil Miller
Phil Miller

Reputation: 38158

For your SKIP goal, you could do something like this:

template <typename U, typename ...Args>
int foo(Args ...args) {
  return foo_helper<U, 0>(std::forward(args));
}

template <typename U, int I, typename ...Args>
int foo_helper(int index, Args ...args) {
  return foo_helper<U, I+1>(std::forward(args));
}

template <typename U, typename ...Args>
int foo_helper<U, SKIP, Args...>(int index, Args ...args) {
  blah = new U(std::forward(args));
  return foobar;
}

Basically, have methods that count up to the target and strip off arguments until it's reached. Make a specialization for the target value.

Also, not that you'll probably want to forward the arguments to preserve references, etc.

I believe C++14 might make some of this easier, but I'm not familiar enough with newer template metaprogramming techniques to address that.

Upvotes: 1

Related Questions