How to define []= and at() = for a custom collection?

Lars Nielsen

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

R Sahu

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related