Variadic Templates example

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

    Recursion is the most general way to program variadic templates, but it's far from the only way. For simple use cases like this, doing a pack expansion directly within a braced initializer list is shorter and likely faster to compile.

    template 
    void print (const Types&... args)
    {   
        using expander = int[];
        (void) expander { 0, (void(cout << args << endl), 0) ...};
    }
    

    In C++17, we'll be able to use a fold expression:

    template 
    void print (const Types&... args)
    {   
        (void(cout << args << endl) , ...);
    }
    

提交回复
热议问题