I want to implement puthon list in cpp, bug do not fin a way to implement pyton's slice operator, e.g.:
list[3:7] // sublist including item 3 included to item 7 excluded
As colon is not an operator in cpp, we cannot overload it. So I changed my implementation to use an overloadable comma, e.g. list[3,7]
. I think I first need to overload comma operator and then overload [ ]
operator
But I am getting error while overloading [ ]
with 2 integers:
Error is : operator[](int, int) must have exactly one argument
Please help me solve the issue.
The C++ standard imposes restrictions on
operator[]
:But the single argument doesn't need to be a scalar. For example:
You can then use this list as explected:
Online demo
However, C++ is not python, so the readers of your code will be very confused by the syntax of (2) and (3). Moreover, I'm not a python expert but I understand that slice operator can be more tricky than that, since there could be start, stop and step and any of those components can be missing.
So I'd recommend not to use a pair as an argument, but create your own slice operator parameters. You could then work on different constructors and default parameters. It could then look like:
But since this would still be quite an unusual indexing scheme, with a view to the principle of least astonishment, I'd strongly recommend to go for the C++ usual practice and simply define the right member functions, e.g. `
This will be self-documenting, without surprise, and easily digested, since it is close to well known semantics of
string::substr()