fold expression

variadic template自C++11引入以来,给程序员带来很大便利,C++17引入fold expression,使用variadic template容易许多。

考虑如下问题,对一个函数的所有参数执行相同的操作,参数的类型不一定相同,参数的个数也不确定,该如何实现?

#include <iostream>
#include <utility>
#include <functional>
#include <string>
template <class T, class... A>
void f(T&& t, A&&... arg)
{
  ((std::forward<T>(t))(std::forward<A>(arg)), ...);
}

int main()
{
  std::string s("world");
  f([](auto&& a) {std::cout << std::forward<decltype(a)>(a) << std::endl; }, 1, 2.3, s);
}

输出

1
2.3
world

上述函数f的实现使用了fold expession和“,”操作符。fold expression支持很多二元操作,如“+”,“*”等。可以方便的实现以前需要复杂的写法才能写出的variadic template。

Posted 2017-06-23