【问题标题】:Ellipsis appears in a parameter declaration of a template function省略号出现在模板函数的参数声明中
【发布时间】:2017-12-22 16:12:36
【问题描述】:

这是来自cppreference 的示例。我不明白模式是如何扩展的。

template<typename ...Ts, int... N> void g(Ts (&...arr)[N]) {}
int n[1];
g<const char, int>("a", n); // Ts (&...arr)[N] expands to 
                            // const char (&)[2], int(&)[1]

Note: In the pattern Ts (&...arr)[N], the ellipsis is the innermost element, not the last element as in all other pack expansions.

问题一:arr 是什么?

问题2:n是一个int数组,是否匹配到int...N?

问题3:怎么会扩展成const char(&)[2], int(&)[1]

【问题讨论】:

  • 查看关于包扩展的任意数量的问题,例如this one
  • 解决问题 2:Ts 是数组类型的类型包,N 是数组维度的 int 包,因此 n 将类型 int 提供到Ts 包,并将维度 1 放入 N 包中。
  • 使用可变参数模板引用 C-Array (int (&amp;a)[42]) 的丑陋语法。
  • 对于 3:"a" 等价于 { 'a', 0 }

标签: c++ templates generic-programming


【解决方案1】:

template <typename ...Ts> void f(Ts&...arr);

基本上等同于

template <typename T0, typename T1, .., typename TN>
void f(T0& arr0, T1& arr1, .., TN& arrN);

对于任何N

同理,

template <typename ...Ts, int... Ns> void g(Ts (&...arr)[Ns]);

相当于

template <typename T0, typename T1, .., typename TN, int N0, int N1, .. int NN>
void g(T0 (&arr0)[N0], T1 (&arr1)[N1], .., TN (&arrN)[NN]);

类型 T (&amp;)[N] 是对大小为 N 且元素类型为 T 的 C 数组的引用

int n[1]; 属于 int [1] 类型。

"a" 的类型为 const char[2] ({'a', '\0'})。

【讨论】:

  • A: void g(T0 (&arr0)[N0], T1 (&arr1)[N1], .., TN (&arrN)[NN]); B: g("a", n);我可以理解您的回答,但是 A 与 B 的匹配度如何?谢谢
  • 那么如果 T0 = const char 且 T1 = int,那么 N0 和 N1 是什么?展开结果中的 2 和 1 来自哪里?
  • @Jerry:已编辑。 "a" 不是 const char* 而是 const char[2]
猜你喜欢
  • 2016-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多