C++ Operator () parenthesis overloading

FurryHead picture FurryHead · Mar 31, 2011 · Viewed 23.5k times · Source

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:

    • A book containing examples/explainations
      Or, a link to online documentation/tutorials

    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.

    Answer

    Adam Casey picture Adam Casey · Mar 31, 2011

    It's called a functor in C++

    This answer has a good example etc

    C++ Functors - and their uses