4

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&. } 
8
  • 2
    And your code looks like...? (How can a function have two different return types?) Commented Oct 9, 2011 at 18:13
  • Can you please provide some code showing us what you've tried? Commented Oct 9, 2011 at 18:14
  • 3
    A function can have different return types, so long as it is disambiguated by its input types (or some template parameter). Commented Oct 9, 2011 at 18:15
  • I think Jonathan's point is the problem I have.. Commented Oct 9, 2011 at 18:17
  • Try to look at the things from the perspective of the compiler. When you say x[i], how should the compiler chose which operator to call? Commented Oct 9, 2011 at 18:18

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I guess it's because both operators have the same arguments, Thank you guys.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.