0
Function Evaluation Order for Variadic Function Template
Hi Please find below code: https://code.sololearn.com/ca5a20A109A0 I thought void test(T val) should be called everytime but it is called only once... Can anyone plz explain why it is so or how the order is evaluated ? I understand the case of test("Test String"); , but rest all is confusing one..
8 Respuestas
+ 1
Ketan Lalcheta This is what is happening: when you invoke test(1,2,"3,4,5") in main, the variadic version of the test function is the one that is chosen.
The parameter val is assigned the value 1 and the parameter pack values is assigned the arguments 2 and "3,4,5".
Inside the variadic test, we call test again, with the parameter pack expanded. In other words, this line of code test(values...); is interpreted by the compiler as test(2,"3,4,5");
This time round, the parameter val is assigned the value 2 and the parameter pack Will only contain "3,4,5";
Inside test, we call test again, for the last time with the expanded parameter pack, which has only argument.Hence the last call to test will look something like this test("3,4,5");
For this last call to test, the compiler will pick the non-variadic version of test, since it's a better match when compared to the variadic one.
And thus "Hi" is printed twice and "*****" only once, since there were two function calls made to the variadic test function
+ 1
[Continuation]
and only one call was made to the non-variadic one.
+ 1
Thanks Anthony Maina
0
Your code works perfectly fine. For example for the second case, each time test() function called with following parameters:
1. test(1, 2, 3, 4, 5) // second test() will be called
2. test(2, 3, 4, 5) // second test() will be called
3. test(3, 4, 5) // second test() will be called
4. test(4, 5) // second test() will be called
5. test(5) // first test() will be called
Same thing goes with test(1, 2, "3, 4, 5").
0
Yeah code is working fine.. why it is calling first test only once from second function call from main
0
The first case called from first function! Because the input of test() is a single string.
0
Let's talk about below code only :
test(1,2,"3,4,5");
Plz remove rest all function call from main apart from above one
Also uncomment cout statement from test method...
Observe output that hi is printed twice not thrice.... There are there parameters like 1 , 2 and third parameter is "3,4,5"
So ideally three time hi should be printed or three times ***** should be printed..
Why such combination of output is observed? Two hi and one *****
I know last argument is remaining and first test is called but how compiler maps this ?
0
This is the purpose of using variadic functions!
We define multiple functions with the same name but with different number of arguments, also each one with it's own implementation!
I don't know how compiler exactly done this but from the C++ point of view, based on the pattern of input arguments, different implementations of same function may called.