C++ Operator () parenthesis overloading
Asked Answered
P

4

18

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.

    Proteolysis answered 31/3, 2011 at 16:55 Comment(0)
    R
    15

    It's called a functor in C++

    This answer has a good example etc

    C++ Functors - and their uses

    Rust answered 31/3, 2011 at 16:58 Comment(0)
    P
    4

    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

    Pirog answered 31/3, 2011 at 16:59 Comment(1)
    That's the first time I heard functioniod. I see from my favorite site of skewed facts. Has anybody else got a definitive reference for this term? A google finds only things links that eventually lead back to parashift. Or is this just another maid up term that is going to cause confusion (and thus its usage be quashed sooner than later).Corves
    D
    1

    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.

    Duomo answered 31/3, 2011 at 16:58 Comment(0)
    D
    0

    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());
    
    Disposal answered 22/6, 2016 at 16:28 Comment(0)

    © 2022 - 2024 — McMap. All rights reserved.