Im trying to get better at C++ by coding up a class for a vector like object.
I wish for it to have an operator overloading for [], that takes in an std::initializer_list<int>
for input of indices on underlying array, and returns a reference to those elements of the array.
So something like this would be possible:
MyVector arr = {1, 2, 3, 4};
arr[{0, 2}] = 3;
// or
arr[{0, 2}] = {5, 6};
What I've thought of is to create another class that inherits MyVector, and write an assignment operator for this class
MyVector::operator[](std::initializer_list<int> ind){
return MyVectorRef(this, ind);
}
class MyVectorRef: private MyVector{
MyVector* base;
std::initializer_list<int> indices;
MyVectorRef(MyVector* base, ind): base(base), indices(ind) {};
MyVector operator=(std::initializer_list<int> cp){
for(int i: indices){
(*base).data[i] = cp[i];
}
}
// similarly for the first case...
};
I know this is very hacky, maybe wont even work. Also, may be of some problem if i wish to have method cascading.
Is there a better way to work around this?