Templated Sum(Args...) variadic function doesn't compile
I used static struct member trick to enforce 2nd pass compilation and still get an error:
struct S
{
template <typename T>
static T Sum(T t) {
return t;
}
template <typename T, typename ... Rest>
static auto Sum(T t, Rest... rest) -> decltype(t + Sum(rest...) )
{
return t + Sum(rest...);
}
};
int main()
{
auto x = S::Sum(1,2,3,4,5);
}
main.cpp:17:14: No matching function for call to 'Sum'
Even using clang 4.0
the compilation fails.
I managed to compile it using decltype(auto)
(solely auto
will work too) instead of the explicit tail return type.
struct S
{
template <typename T>
static T Sum(T t) {
return t;
}
template <typename T, typename ... Rest>
static decltype(auto) Sum(T t, Rest... rest)
{
return t + Sum(rest...);
}
};
I think that the compiler is not able to the deduce the type cause the deduction depends only by a recursive return statement.
More info here
链接地址: http://www.djcxy.com/p/96968.html