如何使用可变参数模板打印出函数的参数?

0x4*_*2D2 2 c++ templates generic-programming function-templates variadic-templates

这个例子使用了一个通用的可变参数模板和函数。我想打印出传递给的参数f

#include <iostream>

template <typename T>
void print(T t) 
{
    std::cout << t << std::endl;
}

template <typename...T>
void f(T &&...args) 
{
    print(args...);
    f(args...);
}

int main() 
{
    f(2, 1, 4, 3, 5);
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

Compilation finished with errors:<br>
source.cpp: In instantiation of '`void f(T ...)` [with `T = {int, int, int, int, int}`]':<br>
source.cpp:16:20: required from here <br>
source.cpp:10:4: error: no matching function for call to '`print(int&, int&, int&, int&, int&)`'<br>
source.cpp:10:4: note: candidate is:<br>
source.cpp:4:6: note: `template<class T> void print(T)`<br>
source.cpp:4:6: note: template argument deduction/substitution failed: 
source.cpp:10:4: note: candidate expects 1 argument, 5 provided
Run Code Online (Sandbox Code Playgroud)

这实际上是我第一次使用可变参数函数,我并不完全了解如何很好地使用它们。

我也不明白为什么这不起作用以及我能做些什么来帮助它。

JeJ*_*eJo 5

更新!

由于这个问题很笼统,而且在 C++17 中你可以做得更好,我想给出两种方法。

解决方案-我

使用折叠表达式,这可能很简单

#include <iostream>
#include <utility>  // std::forward

template<typename ...Args>
constexpr void print(Args&&... args) noexcept
{
   ((std::cout << std::forward<Args>(args) << " "), ...);
}

int main()
{
   print("foo", 10, 20.8, 'c', 4.04f);
}
Run Code Online (Sandbox Code Playgroud)

输出:

foo 10 20.8 c 4.04 
Run Code Online (Sandbox Code Playgroud)

见在线直播


解决方案——二

在 的帮助下if constexpr,现在我们可以避免向递归可变参数模板函数提供基本案例/ 0 参数案例。这是因为编译器if constexpr在编译时丢弃了 false 语句。

#include <iostream>
#include <utility>  // std::forward

template <typename T, typename...Ts>
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<Ts>(rest)...); // pass the rest further
   }
}

int main()
{
   print("foo", 10, 20.8, 'c', 4.04f);
}
Run Code Online (Sandbox Code Playgroud)

输出

foo 10 20.8 c 4.04
Run Code Online (Sandbox Code Playgroud)

见在线直播