views:

43

answers:

4

Hi

this is my generic class:

template<class T, class PrnT>
class PersonalVec {

public:
    PersonalVec();
    T &operator[](int index) const;
    const T &operator[](int index) const;

private:
    std::vector<T> _vec;

};

I'm required to implement 2 versions of [] operator:
one that will return a const reference and a regular one that will also return a reference. When i compile it i get:
PersonalVec.hpp:23: error: ‘const T& PersonalVec<T, PrnT>::operator[](int) const’ cannot be overloaded
PersonalVec.hpp:22: error: with ‘T& PersonalVec<T, PrnT>::operator[](int) const

I've put either one of them as remark and then it does compile, so i guess they are colliding somehow. What is the problem and how can i fix it?

thank you!

+3  A: 

You need:

T &operator[](int index);
const T &operator[](int index) const;

i.e. non-const operator returns non const reference and const one returns the const reference.

Artyom
+2  A: 

You can't overload based on return type, you can only overload based on parameter types, including the hidden this parameter for member functions.

The type of a function call expression, or an expression involving a potentially overloaded operator, is determined by the function type chosen by overload resolution, you cannot force such an expression to have a particular type and try to influence the overload resolution from the return type.

You need to either give your overloaded functions signatures that differ by parameter types or the constness of this, or you need to pick one appropriate return type and have a single function.

Charles Bailey
A: 

You will need to remove constness of the function when returning the non-const reference.

T &operator[](int index);
const T &operator[](int index) const;

Overloading does not and can not happen on the return type.

Manoj R
A: 

Return type of a function is not a criteria that can be used for overloading of functions. A function can be overloaded if:
1. Different no of arguments
2. Differnt Sequence of arguments or
3. Different types of arguments

You are trying to overload the function based on return type and hence it gives the error.
The 'const' keyword can help you overload functions even if the above 3 criterias are not met. So simple solution can be to make one of the function const and keep other as a normal function

Als