I recently asked a question about removing items from a vector. Well, the solution I got works, but I don't understand it - and I cannot find any documentation explaining it.
struct RemoveBlockedHost {
RemoveBlockedHost(const std::string& s): blockedHost(s) {}
// right here, I can find no documentation on overloading the () operator
bool operator () (HostEntry& entry) {
return entry.getHost() == blockedHost || entry.getHost() == "www." + blockedHost;
}
const std::string& blockedHost;
};
to be used as:
hosts.erase(std::remove_if(hosts.begin(), hosts.end(), RemoveBlockedHost(blockedhost)), hosts.end());
I looked at std::remove_if's documentation, it says that it is possible to pass a class instead of a function only when the class overloads the () operator. No information whatsoever.
Does anyone know of links to:
Help with this would be appreciated. I dislike adding code to my software unless I understand it. I know it works, and I am familiar (somewhat) with operator overloading, but I don't know what the () operator is for.
These operators can be overloaded globally or on a class-by-class basis. Overloaded operators are implemented as functions and can be member functions or global functions. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator.
Parentheses ("(" and ")") are operators when used in an expression like a*(b+c) , in which case they're often referred to as grouping operators. When used to set off the type in an expression like (int) x , they're a part of the cast notation ("(" + typename + ")"), not operators.
C does not support operator overloading (beyond what it built into the language).
Unlike all other overloaded operators, you can provide default arguments and ellipses in the argument list for the function call operator. The function call a(5, 'z', 'a', 0) is interpreted as a. operator()(5, 'z', 'a', 0) . This calls void A::operator()(int a, char b, ...) .
It's called a functor in C++
This answer has a good example etc
C++ Functors - and their uses
It's a functionoid, well actually a functor. But the FAQ explains it all:
Functionoids are functions on steroids. Functionoids are strictly more powerful than functions, and that extra power solves some (not all) of the challenges typically faced when you use function-pointers.
https://isocpp.org/wiki/faq/pointers-to-members#functionoids
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With