Variadic Templates example

后端 未结 5 2175
别那么骄傲
别那么骄傲 2021-02-07 20:20

Consider following code, I don\'t understand why empty function of print must be defined.

#include 
using namespace std;

void print()
{   
}   
         


        
5条回答
  •  别跟我提以往
    2021-02-07 20:51

    Because (using a very "simple" level of explanation) the variadic templates mechanism works like a recursion (it is NOT recursion but this is the simplest way to comprehend it), which "consumes" the variadic parameter list, so you will have to define a "stop" function, at which it will recur in the last step of recursion when the "consumed" parameter list is "empty". This was the explanation that I found the easiest to understand this pretty complex notion.

    At the very first step (in main) you will get a function which has the parameters: (int, const char*, int, int, char, const char*)

    Then the variadic parameters are slowly being processed in the variadic function itself, leaving you in the second step with (const char*, int, int, char, const char*) then (int, int, char, const char*) and so on ... till you reach the last element (const char*), and when this is also processed in the next step you end up with (), and the compiler needs this function as a "terminator"

    (Yes, this is very non technical and sounds like grandpa frog telling a story to little froglings ...)

提交回复
热议问题