Variadic Templates example

后端 未结 5 2171
别那么骄傲
别那么骄傲 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:49

    To add on to the other answers, I would like to show what the compiler has to generate for the template calls.

    nm -g -C ./a.out (non-optimized build) gives:

    void print(char const (&) [5])
    void print(char const (&) [5])
    void print(char const (&) [6], int const&, int const&, char const&, char const (&) [5])
    void print(char const (&) [6], int const&, int const&, char const&, char const (&) [5])
    void print(char const&, char const (&) [5])
    void print(char const&, char const (&) [5])
    void print(int const&, char const (&) [6], int const&, int const&, char const&, char const (&) [5])
    void print(int const&, char const&, char const (&) [5])
    void print(int const&, int const&, char const&, char const (&) [5])
    void print(int const&, char const (&) [6], int const&, int const&, char const&, char const (&) [5])
    void print(int const&, char const&, char const (&) [5])
    void print(int const&, int const&, char const&, char const (&) [5])
    print()
    

    You can see all the instantiations of the print function. The final function that ultimately calls print() is void print(char const (&) [5])>

    You can see that when passed an empty parameter pack, the template parameter list must necessarily be empty. Therefore it just calls print(). If you explicitly specified the template parameters, like print(t, args...) you would get infinite recursion.

提交回复
热议问题