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

后端 未结 3 1624
灰色年华
灰色年华 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:27

    c++17 Updates!

    Since the question is general and in C++17 you can do it better, I would like to give two approaches.

    Solution - I

    Using fold expression, this could be simply

    #include 
    #include   // std::forward
    
    template
    constexpr void print(Args&&... args) noexcept
    {
       ((std::cout << std::forward(args) << " "), ...);
    }
    
    int main()
    {
       print("foo", 10, 20.8, 'c', 4.04f);
    }
    

    output:

    foo 10 20.8 c 4.04 
    

    (See Live Online)


    Solution - II

    With the help of if constexpr, now we can avoid providing base case/ 0-argument case to recursive variadic template function. This is because the compiler discards the false statement in the if constexpr at compile time.

    #include 
    #include   // std::forward
    
    template 
    constexpr void print(T&& first, Ts&&... rest) noexcept
    {
       if constexpr (sizeof...(Ts) == 0)
       {
          std::cout << first;               // for only 1-arguments
       }
       else
       {
          std::cout << first << " ";        // print the 1 argument
          print(std::forward(rest)...); // pass the rest further
       }
    }
    
    int main()
    {
       print("foo", 10, 20.8, 'c', 4.04f);
    }
    

    output

    foo 10 20.8 c 4.04
    

    (See Live Online)

提交回复
热议问题