I am confused about the following differences when using with algorithms.
First of all, algorithms work with lambda, functions and functors without any issue. For example,
bool comp (int t1, int t2) {
return t1 > t2;
}
std::array<int, 10> myArray{5, -10, 3, 2, 7, 8, 9, -4, 3, 4};
std::sort(myArray.begin(), myArray.end(), comp);
Now let's define templated comparators,
template<typename T>
bool comp1(T t1, T t2) {
return t1 > t2;
}
struct Comp {
template<typename T>
bool operator()(T t1, T t2) const {
return t1 > t2;
}
};
Comp comp2;
auto comp3 = [](auto t1, auto t2) { return t1 > t2; }
template<typename Container>
void sortDescending(Container &c) {
std::sort(c.begin(), c.end(), comp1); // cannot deduce argument error
std::sort(c.begin(), c.end(), comp2); // works
std::sort(c.begin(), c.end(), comp3); // works
}
sortDescending(myArray);
The function template does not work in the above scenario, which makes me confused.
To me, at least the comp1 and comp2 are almost the same (in the sense that the amount of information required to deduce the argument). But comp1 doesn't work.
So my question is, what is the ultimate reason behind this difference?
I.e., what are the key differences between a function template, a template operator() (template functor?), and a generic lambda in terms of argument deduction?
Thanks.