This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: C++ template function compilation error


llewelly,

I got it. The two operands, both left side and right side, have to be const. That is, if I want to overload the operator< as member function, I have to define this way:

 bool operator<(Integer const& other) const
 {return this->i < other.i;}


Thanks a lot for help!


Take Care.

Jinming

From: llewelly@xmission.com
To: "Jinming Xu" <cybermanxu@hotmail.com>
CC: gcc-help@gcc.gnu.org
Subject: Re: C++ template function compilation error
Date: 20 May 2004 22:48:01 -0600

"Jinming Xu" <cybermanxu@hotmail.com> writes:

> Hello everyone,
>
> I encountered a problem while compiling a C++ program which contains a
> built-in template function sort(). The source of the whole trouble is
> the statement as follows:
>
>   sort(Int.begin(),Int.end());
>
> where Int is a vector containing objects of a class which overloaded
> the operator<().
>
> My program can be compiled with xlC_r successfully.  So I want to know
> whether gcc doesn't completely support template function or there are
> some switches I didn't turn on. The whole code is as follows:
>
> //------code begins-----------------
> #include <iostream>
> #include <vector>
> #include <algorithm>
>
> using namespace std;
>
> class Integer{
> public:
>   int i;
>   Integer(int ii):i(ii){}
>   bool operator<(Integer& other)
>   {return this->i < other.i;}
> };
[snip]

std::sort requires that operator< be able to operate on
    temporaries. But your operator< takes a reference to
    non-const. ISO C++ does not allow a temporary to be bound to a
    reference to non-const. So xlC_r is wrong to accept your code. The
    solution is to define operator< as taking references to const,
    like this:

bool operator<(Integer const& lhs, Integer const& rhs)
  {return lhs.i < rhs.i;}


_________________________________________________________________
Is your PC infected? Get a FREE online computer virus scan from McAfee® Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]