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

标签 c++ templates variadic-templates generic-programming function-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);
}

但我收到以下错误:

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

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

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

最佳答案

更新!

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

解决方案-我

使用 fold expression ,这可能只是

#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);
}

输出:

foo 10 20.8 c 4.04 

( See Live Online )


解决方案-II

if constexpr的帮助下,现在我们可以避免为递归提供基本情况/0 参数情况 variadic template function .这是因为编译器在编译时丢弃了 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);
}

输出

foo 10 20.8 c 4.04

( See Live Online )

关于c++ - 如何使用可变参数模板打印出函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342633/

相关文章:

c++ - 来自 std::map 的前 5 个值

C++:使用模板折叠具有不同类型和功能的重复代码

c++ - 我可以使用模板在 map 中存储不同类型的值吗?

templates - 渲染 Play!Framework2 javascript 作为模板?

c++ - 为什么不能将此参数包直接解包到 vector 初始值设定项列表中?

c++ - 如何更改 .pch 文件位置(Visual Studio 2008)?

c++ - 如何实现这个程序

c++ - CMake、转发声明、信号和 'No such file or directory'

c++ - Variadic 模板化构造函数不接受 x 个参数

c++ - C++ 中包含函数指针的映射