Operator overloading for operator []
.. 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.
a source to share
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.
a source to share
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 [].
a source to share
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.
a source to share