The code below works for the: goal for the left associative sum operation: sum(1,2,3,4);
However, it won't work correctly for sum(1,2,3,4,5)
or sum(1,2,3,4,5,...)
. Anything with more than 4 arguments gives the error:
error: no matching function for call to sum(int, int, int, int, int)
=================================
template <typename T>
T sum(const T& v) {
return v;
}
template <typename T1, typename T2>
auto sum(const T1& v1, const T2& v2) -> decltype( v1 + v2) {
return v1 + v2;
}
template <typename T1, typename T2, typename... Ts>
auto sum(const T1& v1, const T2& v2, const Ts&... rest) -> decltype( v1 + v2 + sum(rest...) ) {
return v1 + v2 + sum(rest... );
}
int main() {
cout << sum(1,2,3,4); //works correctly
//cout << sum(1,2,3,4,5); //compile error
}