开发者

C++ Operator () parenthesis overloading

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() ==开发者_StackOverflow中文版 "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.


    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


    Try and read more about Functors A class that overloads the Function operator() is called a Functor. Any decent C++ book with explanation on STL will have information about it.
    Here is a link you may refer.


    I'd like to point out that after C++11, you can avoid needing something like this with a lambda:

    hosts.erase(std::remove_if(hosts.begin(), hosts.end(),
        [&blockedhost](HostEntry& entry) -> bool {
            return entry.getHost() == blockedHost || entry.getHost() == "www." + blockedHost;
        }), hosts.end());
    
    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新问答

    问答排行榜