为什么C++模板阵列长度扣除需要像“ f(t(& a)[n]”?
使用C ++模板知道C风格数组的长度,我们需要以下操作:
#include<stdio.h>
template<class T,size_t N>
size_t length(T (&a)[N]){ return N; }
int main() {
int fd[2];
printf("%lld\n", length(fd));;
return 0;
}
它有效,打印 2
。我的问题是关于语法的。
在长度
的声明中,为什么该参数应该像(&amp; a)[n]
和 a [n]
没有工作?
如果我更改为
template<class T,size_t N>
size_t length(T a[N]){ return N; }
GCC,会说:
template argument deduction/substitution failed:
couldn't deduce template parameter 'N'
为什么需要额外的&amp; < / code>以及围绕数组标识符的一对括号,在此背后的模板规则 /语法规则是什么?
感谢详细的解释。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在此函数声明中,
编译器会调整具有数组类型的参数,以指向数组元素类型。
也就是说,此声明实际上等同于
另一方面,此调用中用作参数表达式的数组
被隐式转换为指向其第一个元素的指针。
因此,编译器无法推断模板非类型参数N的值。
当将参数声明为参考时,则不会发生这种调整和隐式转换。该参考用作数组的别名。
请注意,使用C函数 printf 您需要使用转换说明器 size_t size_t size_t size_t size_t ,请注意这一点代码> lld 。
zu
而不是<<而不是In this function declaration
the compiler adjusts the parameter having the array type to pointer to the array element type.
That is this declaration actually is equivalent to
On the other hand, the array used as an argument expression in this call
is implicitly converted to a pointer to its first element.
So the compiler cannot deduce the value of the template non-type parameter N.
When the parameter is declared as a reference then such an adjustment and implicit conversion as described above do not occur. The reference serves as an alias for the array.
Pay attention to that to output objects of the unsigned integer type
size_t
with the C functionprintf
you need to use the conversion specifierzu
instead oflld
.