template<typename... ArgTypes>
int add(ArgTypes... args);
template<typename T, typename... ArgTypes>
int add(T t, ArgTypes... args)
{
int sum = 0;
return t + add(args...);
}
template<> int add() {
return 0;
}
How to add more operations like multiplication and subtraction? What does template<> int add() mean?
Could anyone explain in detail how this recursive template works?
UPD: Thank you guys regarding subtraction, yes, subtraction is not commutative so it's not really suitable for such recursive templating.
UPD2: Added a call stack as a reference for community

Here's my attempt at an explanation.
Firstly:
template<typename... ArgTypes>
int add(ArgTypes... args);
This is the starting point. It says "there exists a function called add that takes zero or more generic arguments". It doesn't contain an implementation, so on its own it amounts to a kind of promise to the compiler that such a function will exist.
Then we have:
template<typename T, typename... ArgTypes>
int add(T t, ArgTypes... args)
{
int sum = 0; // This line isn't doing anything!
return t + add(args...);
}
This says "here is a function called add that takes one or more generic arguments". It includes an implementation. Part of that implemantation recursively calls add(args...) with all arguments but the first (i.e. zero or more). We've been told this exists by the first declaration above.
If there is at least one argument in args, then this recursive call will end up calling the the exact same function again. But what happens when args contains zero arguments? We need a version (specialization) of the function to handle that case, which is the only case not handled by our second definition. That's where the third declaration comes in:
template<> int add() {
return 0;
}
This defines a function called add that takes zero arguemnts.
So, in summary:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With