0

I want to create a "grand total" function by summing several other functions together. This can be done at compile time, so I thought a recursive variadic function template would be a good solution. My code so far:

int One(){return 1;}
int Two(){return 2;}
int Three(){return 3;}

using func_t = int(void);

//Base case
template <func_t F>
int Total() {
    return F();
}

template <func_t F, func_t... Fs>
int Total() {
    return F() + Total<Fs...>();
}

int main(int argc, char *argv[])
{
    cout << Total<One, Two, Three>() << endl;
    return 0;
}

However, I get MSVC compiler error C2668: 'Total': ambiguous call to overloaded function; could be int Total<int Three(void),>(void) or int Total<int Three(void)>(void)

I don't understand why the compiler has two similar candidates for my function template, the only difference being that one has an extra comma.

Carlton
  • 4,217
  • 2
  • 24
  • 40
  • 2
    if you can use C++17, you can avoid recursion and, using template folding, simply write `template int Total () { return (Fs() + ...); }` – max66 Nov 07 '18 at 19:13

1 Answers1

2

Your base case declaration is incorrect, and results in the compiler being unable to differentiate between a call to your base case and a call to your recursive base.

If you make your base case an empty list of templates, there is no longer ambiguity.

template <class none = void>
int Total() {
    return 0;
}
merlin2011
  • 71,677
  • 44
  • 195
  • 329