In Functional Programming, what is a functor?

后端 未结 17 660
孤独总比滥情好
孤独总比滥情好 2020-11-28 17:23

I\'ve come across the term \'Functor\' a few times while reading various articles on functional programming, but the authors typically assume the reader already understands

17条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 17:48

    Put simply, a functor, or function object, is a class object that can be called just like a function.

    In C++:

    This is how you write a function

    void foo()
    {
        cout << "Hello, world! I'm a function!";
    }
    

    This is how you write a functor

    class FunctorClass
    {
        public:
        void operator ()
        {
            cout << "Hello, world! I'm a functor!";
        }
    };
    

    Now you can do this:

    foo(); //result: Hello, World! I'm a function!
    
    FunctorClass bar;
    bar(); //result: Hello, World! I'm a functor!
    

    What makes these so great is that you can keep state in the class - imagine if you wanted to ask a function how many times it has been called. There's no way to do this in a neat, encapsulated way. With a function object, it's just like any other class: you'd have some instance variable that you increment in operator () and some method to inspect that variable, and everything's neat as you please.

提交回复
热议问题