Home >Backend Development >C++ >Why Can't I Use Initializer Lists on the Right-Hand Side of Operators in C ?
Initializer Lists and the Right-Hand Side of Operators
Consider the following code snippet:
class foo { }; struct bar { template<typename... T> bar(T const&...) { } }; foo& operator<<(foo& f, bar const&) { return f; } int main() { foo baz; baz << {1, -2, "foo", 4, 5}; return 0; }
Compilers complain about the use of an initializer list on the right-hand side (RHS) of the operator <<. This raises questions about why this is disallowed in C , as opposed to cases where initializer lists are used in function arguments.
Initializer Lists and Expressions
Initializer lists are not expressions as defined in the C Standard. Arguments of functions and operators must generally be expressions. However, the Standard defines exceptions for initializer lists in certain contexts, including as function arguments, subscripts, and assignment expressions.
No Exception for Binary Operators
There is no exception for initializer lists to be used on the RHS (or left-hand side) of binary operators. This prohibition stems from parsing challenges that arise when allowing initializer lists as expressions. Using curly braces for both initializer lists and blocks would lead to ambiguity in the grammar.
Rationale for the Restriction
A proposal to extend the use of initializer lists to expressions was considered in 2007. However, it was determined that allowing initializer lists as right-hand operands of binary operators, but not as left-hand operands, would be too disruptive to the grammar.
Conclusion
Initializer lists cannot be used on the RHS of operators because they are not defined as expressions in the Standard. While certain exceptions exist for their use in specific contexts, allowing them as general operator arguments would pose significant parsing challenges due to the use of curly braces for both initializer lists and blocks.
The above is the detailed content of Why Can't I Use Initializer Lists on the Right-Hand Side of Operators in C ?. For more information, please follow other related articles on the PHP Chinese website!