I
I
IliaNeverov2021-08-05 08:51:32
C++ / C#
IliaNeverov, 2021-08-05 08:51:32

How does this recursion work?

Good afternoon everyone. I have this code:

template <typename T>
void foo(T value) {
    return;
}
template<typename T, typename... Args>
void foo(T value, Args... arg)
{
    std::cout << sizeof(value) << " | ";
    foo(arg...);
}
int main()
{
    MyClass a;//объект какого то класса
    foo(89.8, a, 234.2,3,'a',0);
    return 0;
}

I call the function foo in main once, it calls another function foo in due time, passing a parameter package there, which does nothing and immediately stops its action. In the meantime, it (foo which has a parameter package in its arguments) displays not 1 variable from the parameter package, but everything except the last one, please explain why this is so?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2021-08-05
@IliaNeverov

Because when instantiating the template foo(89.8, a, 234.2,3,'a',0) you get
foo(a, 234.2,3,'a',0)
foo(234.2,3,'a',0) )
foo(3,'a',0)
foo('a',0)
foo(0)
Each function prints its first parameter and calls itself with the parameter pack that cut off the first one.
The last call is to a function that doesn't print anything, so your last parameter isn't printed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question