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;}