tags:

views:

79

answers:

3

hello i am building a template in c++ ,and i need to overwrite the operator "<" inside the template for being able to compare between items inside my data structure. could anyone please tell me how to overwrite it ... should i send a pointer to a function inside the constructor of the template? I got two templates, the first one is Node template which includes a pointer to the data that i am managing. and the second is a Heap template which has an vector of nodes*. in my implementation i should be able to compare between nodes*.

A: 

If the template is for the item type, just assume that they have a comparator, i.e., *node < *node.

DeadMG
what do you mean by assuming that they have a comparator, they dont have a comparator and i need to make 1, my question is where and how should i implement the overwrite.
Nadav Stern
How the hell could you possibly create a comparator for a type you didn't create?
DeadMG
A: 

Overloading operators in C++ is actually pretty easy. Probably what you want to do in your node class is:

template<typename MyData>
class Node {
private:
    MyData data_;
    // ...

public:
    // ...
    bool operator < (Node const &rhs) const;
};

// ...

template<typename MyData>
bool Node<MyData>::operator < (Node const &rhs) const {
    return data_ < rhs.data_;
}

This overloads the < operator in the Node class with a version that just calls the underlying data_ value's < operator.

You can put any code you want inside the function, other than it's name and number of parameters it has no special properties. You can even use this to compare different types or return different values. You could, for example, change rhs in this example to be an int then then you could compare nodes to integers (such as Node n; if (n < 10) ...).

SoapBox
+1  A: 

Will this do? I have purposely provided 'operator <' in the namespace scope so that it is more generic, though it is shown in comments how to do so.

template<class T> struct A;

template<class T, class U>     // Remove U and modify accordingly, if f and s
                               // have to be of the same type.
bool operator < (A<T> const &f, A<U> const &s){
   // have the logic here
   return true;
}

template<class T> struct A{
   // template<class U>                // This is how you define inside a class.
   // bool operator < (A<U> const &s){
   //    have logic here
   //    return true;
   // }
};

int main(){
   A<int> a;
   A<double> d;

   bool b = a < d;
}
Chubsdad