Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading class' operator [] in C++

I have a class which I have written its [] operator, and I want that sometimes the operator will return an int and sometimes a struct.

But the compiler won't let me overload the operator, why?

It says:"...cannot be overloaded"

Code:

template <class T> struct part
{ };


template <class T> class LinkedList
{
         public:
                LinkedList() : size(0), head(0) {}
                T& operator[](const int &loc);
                part<T>& operator[](const int &loc);
};

template <class T> T& LinkedList<T>::operator[](const int &loc)
{
         ..a lot of thing which compiles perfectly
}

template <class T> part<T>& LinkedList<T>::operator[](const int &loc)
{
         ...the same thing but returns struct&.
}
like image 237
Taru Avatar asked Feb 23 '23 18:02

Taru


2 Answers

You can't overload a function based on the return type. You could have your operator return a variant of int and string, and let the user check which was actually returned, but its cumbersome. If the return type can be determined at compilation time, you can implement the operator overloads by mean of having different indices types. Something like this:

struct as_string
{
    as_string( std::size_t index ) : _index( index ){}

    std::size_t const _index;
};

...

int operator[]( int index ) const { ... };
std::string operator[]( as_string const& index ) const { ... };

And then the caller would invoke object[0] to get an int result, or object[as_string(0)] to get a string result.

like image 179
K-ballo Avatar answered Feb 25 '23 08:02

K-ballo


The type of a function's output is not a part of the function's signature. Thus you can't use both int operator[](int index) and Foo operator[](int index).

like image 39
David Hammen Avatar answered Feb 25 '23 09:02

David Hammen