Search code examples
c++language-lawyergrammar

Why are curly braces {} NOT considered an operator in 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++?


Solution

  • 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:
        postfix-expression ( expression-listopt )
        simple-type-specifier   braced-init-list
        [...]

    - [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(), (&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.