Reputation: 699
so assuming I have a series of custom comparators like so:
template <typename T>
class less_class {
bool operator() (T obj, T value) const {
return obj < value;
}
};
template <typename T>
class greater_than {
bool operator() (T obj, T value) const {
return obj > value;
}
};
template <typename T>
class equal_to {
bool operator() (T obj, T value) const {
return obj == value;
}
};
and I have a function like this:
template <typename T>
bool compare_values(T obj, T value, T comparator(T obj, T value)) {
if comparator(obj, value) return true;
return false;
}
What syntax should I use in the compare_values function such that it can take in either one of the aforementioned comparators and use it in its implementation? Currently, my comparator argument to the function is written in a similar way as above and Xcode is throwing a fit with errors. I have tried messing with the arguments a bit to see if anything would work but I think I need to better understand what I am trying to do here. Any help would be appreciated!
Upvotes: 1
Views: 3475
Reputation: 302852
You'd want to just take it as a template:
template <typename T, typename F>
bool compare_values(T const& obj, T const& value, F comparator) {
return comparator(obj, value);
}
bool equal = compare_values(1, 1, less_class<int>{});
Though all of your operator()
's are currently private
, which isn't particularly useful. Also, you're taking all the parameters by value where you should prefer to take them by reference to const to avoid the unnecessary copies.
Also, these already exist as std::less
, std::greater
, and std::equal_to
.
Upvotes: 7