C++ template function compilation error

llewelly@xmission.com llewelly@xmission.com
Fri May 21 04:48:00 GMT 2004


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



More information about the Gcc-help mailing list