开发者

Overloading class' operator [] in C++

开发者 https://www.devze.com 2023-04-12 07:31 出处:网络
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.

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)
开发者_JS百科{
         ..a lot of thing which compiles perfectly
}

template <class T> part<T>& LinkedList<T>::operator[](const int &loc)
{
         ...the same thing but returns struct&.
}


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号