-4

Does anyone know if it's possible to overload the [] operator and update two values with the input.

Example given:

I have the following function in my class now:



    void add(T1 input1, T2 input2)
    {
        // both variables are std::map
        normal_map[input1] = input2;
        reversed_map[input2] = input1;
    }

But I would like to have it that the [] operator updates both values, example:



    class["input1"] = input2; // should do the same as the above add function

Any help will be greatly appreciated

Pimmmo
  • 57
  • 7
  • 1
    Sure, you could make your own class that would do this. – NathanOliver Oct 04 '18 at 21:32
  • @NathanOliver I already have a class, the function specified is a function in the class, that's why I named the variable "class" – Pimmmo Oct 04 '18 at 21:35
  • 1
    Okay, then you just need to provide an [overloaded operator](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) for it. – NathanOliver Oct 04 '18 at 21:36
  • 1
    Also, you can't have a variable named class as class is a keyword. – NathanOliver Oct 04 '18 at 21:37
  • @NathanOliver I also already have an overloaded operator, my question is how to update 2 values, I am able to update 1, but not 2. Also the class variable was meant as example, it's not my actual code – Pimmmo Oct 04 '18 at 21:39
  • 1
    Handy reading: [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – user4581301 Oct 04 '18 at 21:50
  • 1
    Possible duplicate of [Operator\[\]\[\] overload](https://stackoverflow.com/questions/6969881/operator-overload) – Algirdas Preidžius Oct 04 '18 at 21:56

1 Answers1

1

The subscript operator is only meant to give access via a single returned reference (cppreference):

R& T::operator[](S b)

Because of that, you won't be able to access those two maps at once without creating a sort of proxy class, which would make access via the subscript operator very counterintuitive.

eike
  • 1,314
  • 7
  • 18
  • Thanks, I will keep the add method then. Not sure why everybody keeps downvoting my question, as far as I can see it wasn't asked yet – Pimmmo Oct 04 '18 at 21:46
  • @Pimmmo https://stackoverflow.com/questions/6969881/operator-overload – Algirdas Preidžius Oct 04 '18 at 21:51
  • 1
    @Pimmmo See this for a proxy class example (not that I recommend doing this): https://godbolt.org/z/-VybGu – eike Oct 04 '18 at 22:06
  • @Pimmmo As far as the downvotes are concerned, I don't see your question as an exact duplicate of the linked question, even though it has the same answer. Because of this, I don't see any reason to downvote. – eike Oct 04 '18 at 22:07