为什么在C++中花括号{}不被视为运算符?

huangapple go评论155阅读模式
英文:

Why are curly braces {} NOT considered an operator in C++?

问题

我已查看官方操作符列表,但在任何操作符列表(无论是可重新定义还是不可重新定义的)中都没有看到{}出现。

据我所知,{}用于指定代码块,并且用于创建大括号初始化列表,但为什么在C++中不被视为操作符呢?

英文:

I've checked official operator list, but didn't see {} appear in any list of operator (either redefinable or non-redefinable).

As far as I know, {} is used to specify a block of code, and also used to create a braced-init-list, but why is NOT considered an operator in C++?

答案1

得分: 1

使用 {} 和诸如 +!() 等操作符的用法都属于表达式。具体来说,语言的语法包含以下规则(还有许多与表达式相关的规则):

后缀表达式:
    后缀表达式 ( 表达式列表可选 )
    简单类型说明符   花括号初始化列表

这里的第一条规则匹配使用 ()(调用操作符)的函数调用,例如 foo(0)。第二条规则匹配使用给定类型的列表初始化,例如 int{0}

{}() 在语法上非常相似,事实上,将花括号初始化列表视为一个操作符也并不远离事实。然而,有两个特征可以区分操作符:

  1. 操作符通常是可组合的,这意味着你可以构建表达式,比如 x() + y()(&x)()x[0]()。相比之下,花括号初始化列表只能应用于类型名称,用于初始化。{} 不能应用于另一个表达式。
  2. 操作符通常是可以重载的(有一些例外)。列表初始化要么执行某种内置初始化,要么调用构造函数。它不能使用 operator{} 进行重载,这与操作符的预期行为不同。
英文:

Uses of {}, and uses of operators like +, !, (), etc. are expressions. Specifically, the language grammar contains the rule (among many others related to expressions):

> postfix-expression:<br>
> &nbsp;&nbsp;&nbsp;&nbsp;postfix-expression ( expression-list<sub>opt</sub> )<br>
> &nbsp;&nbsp;&nbsp;&nbsp;simple-type-specifier &nbsp; braced-init-list<br>
> &nbsp;&nbsp;&nbsp;&nbsp;[...]

- [expr.post.general]

The first rule matches function calls with () (call operator) such as foo(0). The second rule matches list initialization with a given type, such as int{0}.

{} and () are quite similar gramatically, and it's not far from the truth to think of braced-init-list as an operator too. However, there are two features that distinguish operators:

  1. Operators are usually composable, meaning that you can form expressions like x() + y(), (&amp;x)(), and x[0](). By comparison, braced-init-lists can only be applied to the name of the type, to do initialization. {} cannot be applied to another expression.
  2. Operators are (with some exceptions) overloadable. List initialization is either performing some built-in initialization, or it calls a constructor. It is not overloadable using operator{}, as one would expect from an operator.

huangapple
  • 本文由 发表于 2023年8月11日 00:03:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定