Why the code below does not compile?
template
T sum(T t){
return t;
}
template
auto sum(T t, U... u
In the interests of completeness, since on this version of a similar question, Yakk posted the template specialization solution that I used in the other one, I will provide the ADL solution that he used there:
namespace N {
struct adl {};
template
T sum(A, T t){
return t;
}
template
auto sum(A a, T t, U... u) -> decltype(t + sum(a, u...)) {
return t + sum(a, u...);
}
}
template
auto sum(Args... args) -> decltype(sum(N::adl{}, args...))
{
return sum(N::adl{}, args...);
}
The reason this works is that the sum
used in the trailing-return-type of N::sum
is a dependent name, and has the following lookup rules from [temp.dep.res]:
In resolving dependent names, names from the following sources are considered:
(1.1) — Declarations that are visible at the point of definition of the template.
(1.2) — Declarations from namespaces associated with the types of the function arguments both from the instantiation context (14.6.4.1) and from the definition context.
Since lookup includes declarations that are visible at point of definition and the definition context, N::sum
can find itself recursively.
However, I agree with Yakk that this approach is more confusing.