Operator overloading for operator []

Why do you need to overload the [] operator? I've never come across a practical scenario where it was needed. Can anyone tell me a practical use case.

+2


a source to share


6 answers


.. Err std::vector<t>

, std::basic_string<t>

, std::map<k, v>

and std::deque<t>

?

I used this for the class representing the registry key where I operator[]

returned an object representing the registry value with a string between [] s.



See also Spirit Parser Framework , which uses [] for semantic actions.

+8


a source


Any indexable container can usefully be defined operator[]

for use in any template that uses []

-syntax indexing .

You don't need this syntactic sugar if you're not using generic programming - it might look like , but you can also always define specific named methods like getAt

, setAt

and the like, with similar and easier-to-code functions.



Nonetheless, general programming is at the core of modern C ++ ... and it bears an eerie resemblance to "compilation, a type of reliable duck set" (I'm inclined towards this specific terminology, of course, having a part in its formation - cfr wikipedia ; - ).

Just like you should be trying to use, for example, prefix- *

to mean "dereferencing" for all iterator types and other pointer types (so that they can be duck-typically replaced by pointers in the template!), So you should aim to define operator[]

in types containers where it makes sense, so that they can be quietly replaced with arrays in the appropriate templates.

+4


a source


Useful if you are implementing almost any type of container that provides random access (or at least some form of keyed access) to its elements (consider for example std::vector

).

+3


a source


If you are writing a class that inherits from another class that implements the [] operator, you can overwrite the [] operator, such as std::vector

or std::string

. If you do not, your class may not work as the user expects, because your class implicitly inherits from the parent implementation [].

+1


a source


Well, several STL containers give some examples - vector<>

overloads it to make it act like an array. map<>

, for example, provides an overload operator[]

for providing an "associative array".

+1


a source


While not absolutely necessary, it is incredibly useful in creating custom containers or strings that behave like inline arrays or C strings. This greatly reduces verbosity (for example, in Java, you would need to use x.getElementAt (i) and in C ++ you can use x [i], similarly in Java you need x.compareTo (y) <0, and in C ++ you can achieve the same using x <y). It's syntactic sugar ... but very, very tasty.

+1


a source







All Articles