0

This is probably a duplicate question but I can't seem to find the answer... I'm trying to implement a slicable container like object in C++ using the operator[]. Here's my implementation (which doesn't work):

class SlicableIntVector{
private:
    std::vector<int> vector;
public:
    explicit SlicableIntVector(std::vector<int> vector): vector(vector){};

    // The usual way of overloading operator[]
    int &operator[](int index){
        return vector[index];
    }
    // This version doesn't work as the argument is not binary
    int &operator[](int start, int end){
        return vector[vector.begin()+start, vector.begin()+start+end];
    }

    }
};

Other than just using another method to implement the slicing operation, what options do I have to get slicing working with operator[]? If I could get the flexibility of slicing like a python list I'd be happy.

CiaranWelsh
  • 7,014
  • 10
  • 53
  • 106
  • 2
    Operator `[]` accepts only one argument by design. You may consider using `()` operator instead. – Denis Sheremet Dec 19 '19 at 10:50
  • 1
    [Related thread](https://stackoverflow.com/questions/1936399/c-array-operator-with-multiple-arguments) – Denis Sheremet Dec 19 '19 at 10:51
  • `int &operator[](int start, int end)` -- What were your intentions here? What are you returning a reference to? What you are looking for is equivalent to `std::string_view` or `std::span` (C ++20). Also, trying to make C++ look like another language should be avoided. – PaulMcKenzie Dec 19 '19 at 10:54
  • The built in `std::list` has a [splice](https://en.cppreference.com/w/cpp/container/list/splice) method to move elements from one list to another. – super Dec 19 '19 at 11:23

1 Answers1

2

From n4835:

§12.6.2 Binary operators

1 A binary operator shall be implemented either by a non-static member function (11.4.1) with one parameter or by a non-member function with two parameters

so you can't pass in two parameters.

So try something like:

int &operator[](std::tuple<int, int> start_end);
Paul Evans
  • 27,315
  • 3
  • 37
  • 54