I-16 questions about functors
Posted: December 8th, 2017, 8:59 pm
Hey folks. Got a couple questions about function objects discussed in I-16.
1- This is from http://en.cppreference.com/w/cpp/algorithm/sort:
My question: Why are there no parens after custom function object call customLess, while they are there are after std lib call to std::greater?
2- Chili's implementation of a ThresholdTestY: I get that we're calling the class constructor in compare object by using the braces, but confused about how the () operator gets called when we type:
3- I figured out I could instantiate a ThresholdTestY object and pass it to the sort function, but again, don't quite understand why we're not using parens....
Thanks for any and all insights-- MC
1- This is from http://en.cppreference.com/w/cpp/algorithm/sort:
Code: Select all
// sort using a standard library compare function object
std::sort(s.begin(), s.end(), std::greater<int>());
for (auto a : s) {
std::cout << a << " ";
}
std::cout << '\n';
// sort using a custom function object
struct {
bool operator()(int a, int b) const
{
return a < b;
}
} customLess;
std::sort(s.begin(), s.end(), customLess); //NO PARENS (or braces) AFTER customLess ???
for (auto a : s) {
std::cout << a << " ";
}
std::cout << '\n';
2- Chili's implementation of a ThresholdTestY: I get that we're calling the class constructor in compare object by using the braces, but confused about how the () operator gets called when we type:
Code: Select all
const auto new_end = std::remove_if(vd.begin(), vd.end(), ThresholdTestY{ 20 });
Code: Select all
ThresholdTestY testY(20);
const auto new_end = std::remove_if(vd.begin(), vd.end(), testY);