Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive template explanation C++

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 Call Stack for variadic templates

like image 403
Nusrat Nuriyev Avatar asked Apr 19 '26 20:04

Nusrat Nuriyev


1 Answers

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:

  1. The second declaration defines a function taking one or more arguemnts
  2. The third declaration defines a function taking zero arguments
  3. Together, this means we have a function taking zero or more arguments, as declared by the first declaration.
like image 155
user31601 Avatar answered Apr 22 '26 12:04

user31601