0

I have a template object that can hold different data types, and a method called get(). get() returns the value of the data type cast to an int.

template <class T> 
class A
{
    public:
    int get()
    {
        return (int) m_val;
    }

    void set(T t)
    {
        m_val = t;
    }

    private:
    T m_val;
};

I also have a variadic template function that would take in multiple objects of A, and call their get() methods, adding together the values and returning the result. However, I am fairly new to variadic templates and have no idea what I am doing. This is what I've got, after looking around at them:

//Ensure only types of A can be used for getStuff
template <>
int getStuff<A>(A... t)
{
    int val = 0;
    val = val + (t...).get();
}

int main() {
    A<int> a;
    A<char> b;

    a.set(5);
    b.set(100);

    int val = getStuff(a, b);
    printf("%d", val);
    return 0;
}

Obviously, this does not compile. What am I doing wrong? Do I need to get a pointer to each of the different A's and iterate over them?

prog.cpp:23:13: error: expected initializer before '<' token
 int getStuff<A>(A... t)
             ^
prog.cpp: In function 'int main()':
prog.cpp:37:25: error: 'getStuff' was not declared in this scope
  int val = getStuff(a, b);
Daniel Martin
  • 570
  • 1
  • 9
  • 18
  • 1
    Related: http://stackoverflow.com/q/25680461 – dyp Jan 22 '15 at 00:38
  • 1
    and there is no `A` alone, There is, however, `A` should you decide to provide such a parameter to your *class template* `A`. Regardless, read the link dyp provided. Its important. – WhozCraig Jan 22 '15 at 00:46

1 Answers1

4

You're close ! Here is a non-recursive way, perfect-forwarding included free of charge :

template <class... As>
int getStuff(As&&... as)
{
    int val = 0;
    for(int i : {std::forward<As>(as).get()...})
        val += i;

    return val;
}
Quentin
  • 62,093
  • 7
  • 131
  • 191