这一行声明了一个函数吗? C++
我正在阅读litb关于SFINAE的问题这里并且我想知道他的代码到底声明了什么。 下面是一个更简单的(没有模板)示例:
int (&a())[2];
该声明到底是什么? & 的作用是什么? 更让我困惑的是,如果我声明以下内容,
int b()[2];
则会收到有关声明返回数组的函数的错误,而第一行没有此类错误(因此,人们会认为第一个声明不是 函数)。 但是,如果我尝试分配 a,
a = a;
则会收到一条错误消息,提示我正在尝试分配函数 a...,所以现在它是一个函数。 这东西到底是什么?
I was reading litb's question about SFINAE here and I was wondering exactly what his code is declaring. A simpler (without the templates) example is below:
int (&a())[2];
What exactly is that declaring? What is the role of the &? To add to my confusion, if I declare the following instead
int b()[2];
I get an error about declaring a function that returns an array, while the first line has no such error (therefore, one would think the first declaration is not a function). However, if I try to assign a
a = a;
I get an error saying I'm attempting to assign the function a... so now it is a function. What exactly is this thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
有一些很棒的程序,称为 cdecl 和 c++decl。 它们对于弄清楚复杂的声明非常有帮助,特别是对于 C 和 C++ 用于函数指针的拜占庭形式。
a 返回引用,b 不返回。
There's these awesome programs called cdecl and c++decl. They're very helpful for figuring out complicated declarations, especially for the byzantine forms that C and C++ use for function pointers.
a returns a reference, b does not.
为了便于将来参考,当您有一个特别难以解读的 C/C++ 声明时,您可能会发现此链接很有帮助:
如何阅读 C 声明
为了完整起见,我将重复其他人所说的内容来直接回答您的问题。
...声明 a 为一个零参数函数,它返回对大小为 2 的整数数组的引用。(阅读上面链接上的基本规则,以清楚地了解我是如何想到的)
...声明 b 是一个零参数函数,它返回一个大小为 2 的整数数组。
希望这可以帮助。
For future reference, you may find this link helpful when you have a particularly difficult C/C++ declaration to decipher:
How To Read C Declarations
For completeness, I will repeat what others have said to directly answer your question.
...declares a to be a zero-argument function which returns a reference to an integer array of size 2. (Read the basic rules on the link above to have a clear understanding of how I came up with that.)
...declares b to be a zero-argument function which returns an integer array of size two.
Hope this helps.
它声明了一个符号
a
,它是一个不带参数并返回对两元素整数数组的引用的函数。这声明了一个符号
b
,它是一个不带参数并返回一个二元素整数数组的函数……这在语言的设计中是不可能的。它相对简单:获取运算符优先级图表,以符号名称 (
a
) 开头,然后根据运算符的优先级开始应用运算符。 每次应用操作后记下。It declares a symbol
a
that is a function that takes no arguments and returns a reference to a two-element array of integers.This declares a symbol
b
that is a function that takes no arguments and returns a two-element array of integers... this is impossible by the design of the language.It is relatively simple: get an operator precedence chart, start the symbol name (
a
) and start applying the operators as you see from their precedence. Write down after each operation applied.