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..

20th Jan 2021, 4:08 PM
Ketan Lalcheta
8 ответов
+ 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
22nd Jan 2021, 12:44 PM
Anthony Maina
+ 1
22nd Jan 2021, 12:44 PM
Anthony Maina
+ 1
22nd Jan 2021, 4:15 PM
Ketan Lalcheta
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").
21st Jan 2021, 6:21 AM
0
Yeah code is working fine.. why it is calling first test only once from second function call from main
21st Jan 2021, 12:26 PM
Ketan Lalcheta
0
The first case called from first function! Because the input of test() is a single string.
21st Jan 2021, 12:28 PM