Reputation: 118691
This page on cppreference says:
Built-in subscript operator
The subscript operator expressions have the formexpr1 [ expr2 ] (1)
expr1 [ { expr, ... } ] (2) (C++11)…
2) The form with brace-enclosed list inside the square brackets is only used to call an overloadedoperator[]
Other than this, there's no example or explanation of what it means to use braces inside operator[].
On godbolt.org I verified that, given S s;
, s[{3}]
can be used to call a custom S::operator[](int)
, while if we had S s[5];
then s[{3}]
would be invalid. However, it doesn't seem to work for multiple arguments i.e. s[{3, 4}]
(Clang's error mentions the argument is treated as an initializer list).
So...what's the point of this feature? When would I want to use [{}]
instead of just plain []
?
Upvotes: 4
Views: 839
Reputation: 170123
Its purpose is to allow initialization of any argument type from a brace-init-list. It's added in C++11 to go along with the new initialization syntax, where braces were allowed as initializers for all types (as opposed to just for aggregates).
An example
std::map<std::pair<int, int>, double> m {
// content
};
// later
m[{1, 2}] = 2; // {1, 2} initializes a std::pair which is then used for sub-scripting.
Since a { ... }
is not an expression under the C++ grammar, we can't use {}
in the production [ expr2 ]
. An explicit grammar rule was needed.
Upvotes: 6