user954004
user954004

Reputation: 99

Operator overloading with templates

Im trying to run a program with templates using operator < ,> methods, im getting a compiler error telling me "instantiated from here" and cannot convert Temps<double>' todouble' in return ,,The problem starts when i call the operator function Heres the code..

    template <class T>
class Temps
{   
 private:   
 T a;

 public:
 Temps()
 {
 }
 Temps(T b)
 {
   a=b;
         }     
 T operator<(Temps c)
 {
   if (a < c.a)
   {
      return *this;
   }
   return c;        
 } 
 T operator>(Temps c)              
   {
      if (a > c.a)
      {
         return *this;
      }

      return c;                 
   }   

};

int main()
{

    double d1 = -9.002515,d2=98.321,d3=1.024;

    Temps<double>mag(d1);
    Temps<double>lag(d3);
    Temps<double>tag;
    tag=mag < lag;

    system("pause");
    return 0;
}

Upvotes: -1

Views: 354

Answers (1)

drdwilcox
drdwilcox

Reputation: 3951

Your < and > functions return a T, but you are trying to return a Temps<T>. What you probably want to return is either a or c.a. But the normal semantics of < and > is to return a bool, so you may want to return a < c.a for <:

bool operator <(Temps c) { return a < c.a; }

Similar for >.

Upvotes: 6

Related Questions