2

EDIT: This question is not for overriding the operator [] I know how to do that

I have implemented My own collection class, and for assigning data I would like to provide the same operators/functions as std::vector. However, I have not been able to find a way to define the operators [index]=elm and at(index) = elm.

I am not even completely sure what to terms to search for as these two are not exactly operators

Lars Nielsen
  • 2,005
  • 2
  • 25
  • 48
  • https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading – R Sahu Mar 19 '19 at 20:23
  • There's no operator `at` - it is a function in `std` containers. And, for `[]`, there is `operator[]`. – Algirdas Preidžius Mar 19 '19 at 20:24
  • See [this](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) on how the `operator[]` should be declared. `at` will match that. – NathanOliver Mar 19 '19 at 20:24
  • Notice how I write `[]=` and `at()=` not `[]` and `at()` only. The two later I have already overridden :) – Lars Nielsen Mar 19 '19 at 20:29
  • 3
    Your `operator[]` and `at` function should return a reference to an element of your collection - you don't need to add anything to have assignment to those work – UnholySheep Mar 19 '19 at 20:31
  • 1
    @LarsNielsen: "*Notice how I write []= and at()= not [] and at() only.*" There is no such thing as `[]=` or `at()=`. It's merely `[]` *followed by* an `=`. – Nicol Bolas Mar 19 '19 at 20:37
  • @NicolBolas thank you :) Also why I wrote that these are not exactly operators, I just had zero clue what it was called :) – Lars Nielsen Mar 19 '19 at 20:39

2 Answers2

4

Define your operator[] overload and your at function to return a reference to the specified item. You can then assign the new value through that reference.

jkb
  • 2,376
  • 1
  • 9
  • 12
2

There is no []= operator. If your operator[] function returns a reference that can be assigned to, that's all you need.

Simple example to demonstrate the idea.

struct Foo
{
    int i;
    int& operator[](int) { return i; };
    int operator[](int) const { return i; };
}

Now you can use

Foo f;
f[10] = 20;   // The index is not used by Foo::operator[]
              // This is just to demonstrate the syntax.

You need to do the same with the at() function.

R Sahu
  • 204,454
  • 14
  • 159
  • 270