Re: C++ template function compilation error

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



"Jinming Xu" <cybermanxu@xxxxxxxxxxx> 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;}


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux