• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 173
  • Last Modified:

How do I create a template for this ?

Hi experts,

 I have following code :
//----------
bool operator<(const Box &lh, const Box &rh)
{
    if (lh.x != rh.x) return (lh.x < rh.x);
    return (lh.y < rh.y);
}
//---------------

how do I make a template for the above code ?
therefore, when Box --> Animal
                         x --> head
                         y --> tail

I can easily reuse the code ???

many thanks !
0
meow00
Asked:
meow00
3 Solutions
 
andrewjbCommented:
You can template it so to let you change 'Box' to 'Animal', but you can't really get it to use different variables e.g. head rather than x.

Perhaps you should define a pair<> which, for Box is (x,y) and for Animal is (head,tail), then use that somehow. Give Box and Animal a method like GetPair(), and do it like:

template < class C >
bool operator<( const C &lh , const C &rh )
{
  if ( lh.GetPair().first != rh.GetPair().first ) return ( ... etc.

}
0
 
dog_Commented:
meow,

You could template the operator like so...

template <class T>
bool operator< (T lhs, T rhs)
{
      if(lhs.x < rhs.x)
            return true;
      return (lhs.y<rhs.y);
}

This assumes that there is an x and a y in the class. This is not a good assumption and will cause headaches in the long run. The way to deal with this is to have each class define the < operator in a way that is meaningful for the class. That way you don't force constraints on other classes to conform to the interface for a template function.
0
 
rendaduiyanCommented:
Your opearor must be contained in a class, otherwise you can not overload global operator <
with template.
If so, you can use template specifications:
//for general class Box
template <class T>
class A
{
bool operator<(const T &lh, const T &rh)
{
    if (lh.x != rh.x) return (lh.x < rh.x);
    return (lh.y < rh.y);
}
}
//specifications
template<>
class A<Animal>
{
    bool operator<(const T &lh, const T &rh)
{
    //change the comparing target.
}

}

0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now