为什么C++模板阵列长度扣除需要像“ f(t(& a)[n]”?

发布于 2025-02-11 01:59:07 字数 705 浏览 1 评论 0 原文

使用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>以及围绕数组标识符的一对括号,在此背后的模板规则 /语法规则是什么?

感谢详细的解释。

Use C++ template to know the length of C-style array, we need this:

#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;
}

It works, prints 2. My question is about the syntax.

In the declaration of length, why the parameter should be like (&a)[N], and a[N] doesn't work?

If I change to

template<class T,size_t N>
size_t length(T a[N]){ return N; }

gcc will say:

template argument deduction/substitution failed:
couldn't deduce template parameter 'N'

Why need an extra & and a pair of braces around array identifier here, what's the template rule / syntax rule behind this?

Appreciate detailed explanations.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

反差帅 2025-02-18 01:59:07

在此函数声明中,

template<class T,size_t N>
size_t length(T a[N]){ return N; }

编译器会调整具有数组类型的参数,以指向数组元素类型。

也就是说,此声明实际上等同于

template<class T,size_t N>
size_t length(T *a){ return N; }

另一方面,此调用中用作参数表达式的数组

length(fd)

被隐式转换为指向其第一个元素的指针。

因此,编译器无法推断模板非类型参数N的值。

当将参数声明为参考时,则不会发生这种调整和隐式转换。该参考用作数组的别名。

请注意,使用C函数 printf 您需要使用转换说明器 zu 而不是<<而不是 size_t size_t size_t size_t size_t ,请注意这一点代码> lld 。

In this function declaration

template<class T,size_t N>
size_t length(T a[N]){ return N; }

the compiler adjusts the parameter having the array type to pointer to the array element type.

That is this declaration actually is equivalent to

template<class T,size_t N>
size_t length(T *a){ return N; }

On the other hand, the array used as an argument expression in this call

length(fd)

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 function printf you need to use the conversion specifier zu instead of lld.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文