无法理解C ++中的可变参数模板 [英] can't understand variadic templates in c++

查看:68
本文介绍了无法理解C ++中的可变参数模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关可变参数模板的信息,我遇到了这个示例。本书提到要结束递归过程,需要使用函数 print()。我真的不明白它的用途。作者为什么使用此空的 print()函数?

I was reading about variadic templates and I came across this example. The book mentions that to end the recursion process, the function print() is used. I really can't understand its use. Why does the author use this empty print() function?

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个参数或更多

A variadic expression can capture 0 arguments or more.

例如调用 print(1) 。然后 T 捕获 int Types = {} -不捕获任何参数。因此,调用 print(args ...); 扩展为 print(); ,这就是为什么您需要一个基本情况。

Take for example the call print(1). Then T captures int and Types = {} - it captures no arguments. Thus the call print(args...); expands to print();, which is why you need a base case.

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

You don't need the recursion at all. I always use the following debuglog function in my code (modified for your needs):

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)表示您现在喜欢的任何内容。

Because this variadic function takes at least one argument, you are free to use print(void) for whatever you like now.

这篇关于无法理解C ++中的可变参数模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆