JustinWu
JustinWu

Reputation: 11

C++: overloading subscript operator (different return typ)

I know that a return value is not enough to override a function (and I read different threads about it on stackoverflow), but is there a way to overload the subscript operator of a class, just to return the value (I can't changed to to return by reference-type of function)

It has to look like or at least work like:

What's the best approach to solve this problem (It has to be a operator)?

Update: The Problem is, that's not allowed to just overload a member or operator just with the return type.

struct A {int a; int b; double c;};
struct B {int a; int b; array<double,2> c;};

class Whatever
{
public:
A operator [](unsigned int ) const; //it's just reading the element
B operator [](unsigned int ) const;
}

A operator [](unsigned int Input){
//...
}

B operator [](unsigned int Input){
//...
}

Upvotes: 1

Views: 579

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153820

Assuming you know what kind of type you are going to access, you can return a proxy which converts to either type and, probably, does the access upon conversion. Since you want to access a const object that should be fairly straight forward. Things get a bit more messy when trying to do the same for an updating interface:

class Whatever;
class Proxy {
    Whatever const* object;
    int             index;
public:
    Proxy(Whatever const* object, int index)
        : object(object)
        , index(index) {
    }
    operator A() const { return this->object->asA(this->index); }
    operator B() const { return this->object->asB(this->index); }
};
class Whatever {
    // ...
public:
    Proxy operator[](int index) { return Proxy(this, index); }
    A asA(index) { ... }
    B asB(index) { ... }
};

The main constraint is that you can't access members of A and B directly: you need to convert to an A or a B first. If the two types are actually known, you can created a Proxy which forwards the respective member function appropriately. Of course, if there are commonly named member functions or data members you'll need to explicitly convert first.

Upvotes: 2

Related Questions