What are C++ functors and their uses?

后端 未结 14 1463
花落未央
花落未央 2020-11-21 04:27

I keep hearing a lot about functors in C++. Can someone give me an overview as to what they are and in what cases they would be useful?

14条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 04:49

    Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.

    Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy functor that multiplies its argument by a specified amount:

    class MultiplyBy {
    private:
        int factor;
    
    public:
        MultiplyBy(int x) : factor(x) {
        }
    
        int operator () (int other) const {
            return factor * other;
        }
    };
    

    Then you could pass a MultiplyBy object to an algorithm like std::transform:

    int array[5] = {1, 2, 3, 4, 5};
    std::transform(array, array + 5, array, MultiplyBy(3));
    // Now, array is {3, 6, 9, 12, 15}
    

    Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.

提交回复
热议问题