Reputation: 311
It is possible to distinguish when template parameter in functor represents an object or a pointer to object?
class Comparator
{
public:
template <typename Object>
bool operator() ( const Object &o1, const Object &o2 ) const
{
return ( o1.getID() < o2.getID() );
}
template <typename Object>
bool operator() ( const Object *o1, const Object *o2 ) const
{
return ( o1->getID() < o2->getID() );
}
};
Objects or pointers are stored in generic container List, that should be sorted using the Comparator class
int main()
{
List <Object *> objects1;
std::sort(objects1.begin(), objects1.end(), Comparator());
List <Object> objects2;
std::sort(objects2.begin(), objects2.end(), Comparator());
);
Currently I am using two comparators (Comparator1, Comparator2) but I do not find it comfortable...
Upvotes: 1
Views: 454
Reputation: 139
You could templatetify the Comparator
itself:
template<typename Object>
class Comparator {
public:
bool operator()(const Object &o1, const Object &o2) const {
return (o1.getID() < o2.getID());
}
bool operator()(const Object *o1, const Object *o2) const {
return (o1->getID() < o2->getID());
}
};
int main() {
std::vector objects1;
std::sort(objects1.begin(), objects1.end(), Comparator<Object> ());
std::vector objects2;
std::sort(objects2.begin(), objects2.end(), Comparator<Object> ());
return 0;
}
This way it doesn't even generate two separate comparators!
Upvotes: 4
Reputation: 101456
Given your architecture (one list of Object
s, another of Object*
s) you really have no alternative.
Do you really need two lists?
Upvotes: 0