How do I print out the arguments of a function using a variadic template?

后端 未结 3 1620
灰色年华
灰色年华 2020-12-12 01:17

This example uses a common variadic template and function. I want to print out the arguments passed to f:

#include 

template <         


        
3条回答
  •  执笔经年
    2020-12-12 01:19

    There you go. You had several mistakes in your code, you can see the comments between the lines below:

    #include 
    
    template 
    void print(T t) {
       std::cout << t << std::endl;
    }
    
    // Base case, no args
    void f() {}
    
    // Split the parameter pack.
    // We want the first argument, so we can print it.
    // And the rest so we can forward it to the next call to f
    template 
    void f(T &&first, Ts&&... rest) {
        // print it
        print(std::forward(first));
        // Forward the rest.
        f(std::forward(rest)...);
    }
    
    int main() {
        f(2, 1, 4, 3, 5);
    }
    

    Note that using rvalue refs here makes no sense. You're not storing the parameters anywhere, so simply passing them by const reference should do it. That way you'd also avoid using std::forward just to keep the (useless) perfect forwarding.

    Therefore, you could rewrite f as follows:

    template 
    void f(const T &first, const Ts&... rest) {
        print(first);
        f(rest...);
    }
    

提交回复
热议问题