I want to write a simple adder (for giggles) that adds up every argument and returns a sum with appropriate type.
Currently, I’ve got this:
#include <iostream>
using namespace std;
template <class T>
T sum(const T& in)
{
return in;
}
template <class T, class... P>
auto sum(const T& t, const P&... p) -> decltype(t + sum(p...))
{
return t + sum(p...);
}
int main()
{
cout << sum(5, 10.0, 22.2) << endl;
}
On GCC 4.5.1 this seems to work just fine for 2 arguments e.g. sum(2, 5.5) returns with 7.5. However, with more arguments than this, I get errors that sum() is simply not defined yet. If I declare sum() like this however:
template <class T, class P...>
T sum(const T& t, const P&... p);
Then it works for any number of arguments, but sum(2, 5.5) would return integer 7, which is not what I would expect.
With more than two arguments I assume that decltype() would have to do some sort of recursion to be able to deduce the type of t + sum(p…). Is this legal C++0x? or does decltype() only work with non-variadic declarations? If that is the case, how would you write such a function?
I think the problem is that the variadic function template is only considered declared after you specified its return type so that
sumindecltypecan never refer to the variadic function template itself. But I’m not sure whether this is a GCC bug or C++0x simply doesn’t allow this. My guess is that C++0x doesn’t allow a “recursive” call in the->decltype(expr)part.As a workaround we can avoid this “recursive” call in
->decltype(expr)with a custom traits class:This way, we can replace
decltypein your program withtypename sum_type<T,P...>::typeand it will compile.Edit: Since this actually returns
decltype((a+b)+c)instead ofdecltype(a+(b+c))which would be closer to how you use addition, you could replace the last specialization with this: