Overloading reference operator

Axel Freyn axel-freyn@gmx.de
Mon Apr 26 06:13:00 GMT 2010


Hi,
On Sun, Apr 25, 2010 at 02:39:09PM +0100, Andrew Haley wrote:
> On 04/25/2010 04:44 AM, Samkit Jain wrote:
> > Yes my question is why does'nt assignment operator work out of the box ?
> 
> But why should it?  You haven't defined one.

I believe the problem to be the following:
For the builtin-types, many candidate operator functions are already
predefined, for example

int& operator ++(int &);
int operator ++(int &, int);
int& operator =(int &, const int &);

for pre-increment, post-increment and assignment of integers.

Now, the way I understand overload resolution for 

MyClass<int> instance;

the following will happen:

a) "instance++;" or "++instance;" and all other unary/binary operators
except assignment operators:
Those can be either defined as member functions of MyClass, or by
non-member functions with one/two parameters. This allows the compiler
to find the predefined operator functions like int& operator ++(int &),
which can be used after converting MyClass<int> to int& using the
reference operator &.

b) "instance=1" oder "instance=instance+1" or any other assignment: 
Assignment operators have to be defined as member-functions of MyClass -
it is NOT possible to define assignment operators as
non-member-functions. Thus, during overload-resolution for an assignment
operators, the compiler does NOT try non-member functions, an thus it
does NOT find "int& operator =(int &, const int &);"


So as Andrew already suggested, it will only work when you define
explicitely as member-function an assignment operator which can be used
in this situation.


HTH,

Axel

> > On Sun, Apr 25, 2010 at 12:02 AM, Andrew Haley <aph@redhat.com> wrote:
> >> On 04/24/2010 07:07 PM, Andrew Haley wrote:
> >>> On 04/24/2010 06:30 PM, Samkit Jain wrote:
> >>>> template<class T>
> >>>> MyClass
> >>>> {
> >>>>  public:
> >>>>     MyClass() : m_data(10) { }
> >>>>     operator T&() { return m_data; }
> >>>>  private:
> >>>>     T m_data;
> >>>> };
> >>>
> >>> I think this example does what you want:
> >>>
> >>> template<class T> class
> >>> MyClass
> >>> {
> >>> public:
> >>>   MyClass() : m_data(10) { }
> >>>   operator T&() { return m_data; }
> >>>   T& operator= (const T &t) { m_data = t; return *this; }
> >>> private:
> >>>   T m_data;
> >>> };
> >>
> >> I'm sorry, I think I misunderstood your question.  You're asking why
> >>
> >>  instance++;
> >>
> >> works, but, say
> >>
> >>  instance = instance + 1;
> >>
> >> doesn't.  Apologies.
> >>
> >> Andrew.
> >>



More information about the Gcc-help mailing list