studying variadic fails

Apparently the question has been deleted, but bizarrely, it was an exact copy of http://www.cplusplus.com/forum/general/267514/ , as abdulbadii has mentioned below (it was his original question).


----
Because you're creating a new object every recursion. So s always starts as 0. You could make it static:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <class T>
struct Accumulate {
    static T s;

    Accumulate() { }

    template <class...TL>
    Accumulate<T>(T head, TL...tail) {
        s += head;
        Accumulate(tail...);
    }
};

template <class T> T Accumulate<T>::s = 0;

#include <iostream>

int main() {
    Accumulate<int> a(1, 2, 3, 4, 5);
    std::cout << "total = " << a.s << "\n";
}

Last edited on
This type conversion inside the constructor body:
Accumulate(tail...)
Creates a new object of type Accumulate and discards the result.

You need to do something to *this with the result :
1
2
3
4
5
6
7
8
9
10
11
12
13
template <class T>
    struct Accumulate {
      T s;
        
    Accumulate() 
      : s() 
    {}
    
    template <class H, class...TL>
    Accumulate(H head, TL...tail) 
      : s(head + Accumulate(tail...).s)   
    {}
};


Consider a fold-expression:
1
2
3
4
5
6
7
template <class T> struct Accumulate {
    T s;
    
    template <class... Ts> Accumulate(Ts... args) 
      : s((T() + ... + args))
    {}
};


http://coliru.stacked-crooked.com/a/c8ab929ffc8da46a
Last edited on
please OP don't pirate question : http://www.cplusplus.com/forum/general/267514/
instead we'd all merge into it
Topic archived. No new replies allowed.