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*.
If the template is for the item type, just assume that they have a comparator, i.e., *node < *node.
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) ...
).
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;
}