通过参数包扩展添加所有参数 [英] Add all parameters with parameter pack expansion

查看:49
本文介绍了通过参数包扩展添加所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下,我有一个带有 int ... 参数的可变参数模板.例如这样的函数:

Consider I have a variadic template with int... parameters. For example a function like this:

template<int... t>
int add(){
    return t... + ???
}

该方法应该做的就是添加所有参数.使用递归可变参数模板可以轻松实现.但是,是否还可以使用参数包扩展来表达这一点(或类似的表达方式,例如使用其他二进制运算符聚合所有模板参数)?

All the method should do is adding all the parameters. It can be easily achieved using recursive variadic templates. However, is it also possible expressing this (or something similar like using other binary operators to aggregate all the template parameters) using parameter pack expansion?

推荐答案

是的,使用我从休息室的@Xeo中学到的技巧.我最初使用它来创建可变的打印"模板功能.

Yes, using a trick I learnt from @Xeo in the Lounge. I originally used it to make a variadic "print" template function.

#include <iostream>

template<int... ints>
int add()
{
  int result = 0;
  using expand_variadic_pack  = int[]; // dirty trick, see below
  (void)expand_variadic_pack{0, ((result += ints), void(), 0)... };
  // first void: silence variable unused warning
  // uses braced-init-list initialization rules, which evaluates
  //  the elements inside a braced-init-list IN ORDER, to repetetively
  //  execute a certain operation
  // second void is to prevent malicious "operator," overloads, which
  //  cannot exist for void types
  // 0 at the end is to handle empty variadic pack (zero-size array initializer is illegal.
  return result;
}

int main()
{
  std::cout << add<1,2,3,4>() << '\n';
}

这适用于所有具有不错的C ++ 11支持的编译器(GCC 4.8 +,Clang 3.2 +,MSVS2013等)

This works on every compiler that has decent C++11 support (GCC 4.8+, Clang 3.2+, MSVS2013, ...)

这篇关于通过参数包扩展添加所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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