I am trying to write a variation pattern constexpr that calculates the sum of the given template parameters. Here is my code:
template<int First, int... Rest> constexpr int f() { return First + f<Rest...>(); } template<int First> constexpr int f() { return First; } int main() { f<1, 2, 3>(); return 0; }
Unfortunately, it does not compile error message error C2668: 'f': ambiguous call to overloaded function when trying to resolve the call f<3,>() .
I also tried changing the underlying recursion case to accept 0 template arguments instead of 1:
template<> constexpr int f() { return 0; }
But this code also does not compile ( error C2912: explicit specialization 'int f(void)' is not a specialization of a function template message error C2912: explicit specialization 'int f(void)' is not a specialization of a function template ).
I could extract the first and second arguments of the template for compilation and work, for example:
template<int First, int Second, int... Rest> constexpr int f() { return First + f<Second, Rest...>(); }
But this is not the best option. So the question is: how to write this calculation in an elegant way?
UP: I also tried to write this as one function:
template<int First, int... Rest> constexpr int f() { return sizeof...(Rest) == 0 ? First : (First + f<Rest...>()); }
And this also does not work: error C2672: 'f': no matching overloaded function found .