Class overload of 'operator [] in C ++

I have a class that I wrote it [], and I want the statement sometimes to return int , and sometimes struct .

But the compiler will not let me overload the operator, why?

It says: "... you must not overload"

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&. } 
+4
source share
2 answers

You cannot overload a function based on the return type. You can force your operator to return an int and string variant, and let the user verify that it was indeed returned, but it is cumbersome. If the type of the return value can be determined at compile time, you can implement operator overloads, bearing in mind the different types of indexes. Something like that:

 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 called object[0] to get the result of int , or object[as_string(0)] to get the result of string .

+6
source

The function output type is not part of the function signature. Thus, you cannot use both int operator[](int index) and Foo operator[](int index) .

+2
source

All Articles