Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/149.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 折叠表达式与编译递归_C++_C++11_C++17_Sfinae_Fold Expression - Fatal编程技术网

C++ 折叠表达式与编译递归

C++ 折叠表达式与编译递归,c++,c++11,c++17,sfinae,fold-expression,C++,C++11,C++17,Sfinae,Fold Expression,在c++17中,我们使用了fold表达式,它可以大大简化代码,否则可以使用编译器递归和SFINAE或重载来实现这些代码。 例如,在下面的代码中 #include <iostream> #include <utility> template<typename ...Args> void printer(Args&&... args) { (std::cout << ... << args) << '\n'

c++17
中,我们使用了fold表达式,它可以大大简化代码,否则可以使用编译器递归和SFINAE或重载来实现这些代码。 例如,在下面的代码中

#include <iostream>
#include <utility>

template<typename ...Args>
void printer(Args&&... args) {
  (std::cout << ... << args) << '\n';
}

void printer_cpp11() { }

template <typename First, typename ...Args>
void printer_cpp11(First&& first, Args&&... args)
{
  std::cout << first;
  printer_cpp11(std::forward<Args>(args)...);
}

int main()
{
  printer(3, 4, "hello");

  std::cout << std::endl;

  printer_cpp11(3, 4, "hello");

  return 0;
}
#包括
#包括
模板
无效打印机(Args&&…Args){

(std::cout编译器将为每个具有不同参数的调用创建一个新的打印机实例,并在函数中展开操作符由于内联,这两个版本将导致相同的codegen,因此运行时性能完全相同:(清除流混乱的代码)


然而,与递归实例化相比,使用折叠表达式的编译时间和内存使用情况预计要好得多,正因为如此,折叠表达式通常是首选。更不用说,它们还提供了更清晰、更易于推理的代码。

只需添加到@SergeyA的答案中,您就可以减少对递归和空函数在c++11版本中通过执行类似于

template <typename ...Args>
void printer_cpp11_norecursion( Args&&... args)
{
  using do_ = int[];
  do_{0,
    (std::cout << args,0)...
  };
}
模板
无效打印机\u cpp11\u取消执行(Args&&…Args)
{
使用do_uz=int[];
做{0,

(std::cout By
printer(std::forward(args);
我想你指的是
printer_cpp11(std::forward(args).)
,对吗?我认为
打印机\u cpp11
应该调用它自己,而不是
打印机
假设无法完成,但是为什么不分析它呢。@L.F.当然,修复了打印错误
打印机\u cpp11
将导致编译器递归实例化
大小的…(Args)
不同的模板函数-这是模板膨胀和编译速度慢的常见情况谢谢,这是我第一次看到这种语法。您正在用0初始化
int
数组,丢弃调用
cout
的结果,对吗?