Operator Overloading and Initializer Lists on RHS
In C programming, initializer lists are a concise syntax to initialize aggregate objects with a list of expressions. While initializer lists can be conveniently employed in various scenarios, their usage on the right-hand side (RHS) of operators has been a point of discussion.
Why Initializer Lists Are Restricted on RHS
C 11 does not allow initializer lists on the RHS of operators, including the binary operator << used in your code. There are a few reasons for this restriction:
Exceptions for Initializer Lists
Despite the general restriction on using initializer lists in operator arguments, C does define specific exceptions where initializer lists are accepted:
In your code, you can use an initializer list as an argument to the bar constructor, which is called within the << operator:
foo baz; baz << bar{1, -2, "foo", 4, 5}; // Legal
Reasons for the Restriction
The decision to restrict initializer lists on the RHS of operators stems from the desire to maintain a consistent and clear grammar. Allowing initializer lists in all contexts would have introduced additional complexity and potential ambiguity in the language.
As noted in the discussion paper mentioned in your question, the alternative of allowing initializer lists on the RHS but not the LHS was considered too problematic. Therefore, the conservative approach of allowing initializer lists only in specific contexts was chosen.
The above is the detailed content of Why Can't I Use Initializer Lists on the Right-Hand Side of C Operators?. For more information, please follow other related articles on the PHP Chinese website!