问题
I am trying to a template class driven with a template parameter of std::less, std::greater or. This is a follow up to this question since, the answer doesn't provide a full example and I am unable to successfully use the template comparator.
#include <functional>
#include <algorithm>
template <typename C>
class Test
{
int compare(int l, int n, int x, int y)
{
public:
bool z = C(x, y);
if(l < n && z)
{
return 1;
}
else
{
return 2;
}
}
};
int main() {
Test<std::less<int>> foo;
Test<std::greater<int>> bar;
foo.compare(1, 2, 3, 4);
bar.compare(1, 2, 3, 4);
}
回答1:
Note that C (i.e. std::less<int> or std::greater<int>) is the type name, not the instance. bool z = C(x, y); won't work when C==std::less<int>, because C(x, y) will be interpreted as the construction of std::less<int>, which will fail because std::less doesn't have such constructor, and std::less can't be converted to bool.
You might mean call operator() on the instance of C, you could change it to
bool z = C()(x, y);
来源:https://stackoverflow.com/questions/38558746/full-example-of-using-template-comparator