c++ - 无法理解 C++ 中的可变参数模板

标签 c++ templates c++11 variadic-templates

我在阅读可变参数模板时遇到了这个例子。书中提到要结束递归过程,使用函数print()。实在看不懂它的用途。为什么作者要使用这个空的 print() 函数?

void print () // can't get why this function is used
{
}

template <typename T, typename... Types>
void print (const T& firstArg, const Types&... args)
{
    std::cout << firstArg << std::endl; // print first argument
    print(args...); // call print() for remaining arguments
}

最佳答案

可变参数表达式可以捕获 0 个或更多参数

以调用 print(1) 为例。然后 T 捕获 intTypes = {} - 它不捕获任何参数。因此调用 print(args...); 扩展为 print();,这就是为什么你需要一个基本案例。


你根本不需要递归。我总是在我的代码中使用以下 debuglog 函数(根据您的需要进行修改):

template<typename F, typename ... Args>
  void
  print(const F& first, const Args&... args) // At least one argument
  {
    std::cout << first << std::endl;
    int sink[] =
      { 0, ((void)(std::cout << args << std::endl), 0)... };
    (void) sink;
  }

因为这个可变参数函数至少接受一个参数,所以您现在可以随意使用 print(void) 做任何您喜欢的事情。

关于c++ - 无法理解 C++ 中的可变参数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30937379/

相关文章:

c++ - "error C2678: binary ' = ' : no operator found which takes a left-hand operand of type..."使用lambda函数进行 map 过滤时

c++ - 在 C++ 中将两个矩阵相乘

c++ - 检索元素时数组发生变化

具有动态选择的 C++ 模板类型

c++ - vector 和push_back()

templates - 未知类型名称 ‘vector’

c++ - 为什么这部分代码被忽略了?

c++ - 为什么此代码与运算符(operator)错误不匹配?

c++ - ld : duplicate symbol

c++ - 我应该在服务器端做什么,以便从 crashpad 库中收集小型转储?