What are C++ functors and their uses?

后端 未结 14 1457
花落未央
花落未央 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条回答
  •  醉话见心
    2020-11-21 04:58

    A Functor is a object which acts like a function. Basically, a class which defines operator().

    class MyFunctor
    {
       public:
         int operator()(int x) { return x * 2;}
    }
    
    MyFunctor doubler;
    int x = doubler(5);
    

    The real advantage is that a functor can hold state.

    class Matcher
    {
       int target;
       public:
         Matcher(int m) : target(m) {}
         bool operator()(int x) { return x == target;}
    }
    
    Matcher Is5(5);
    
    if (Is5(n))    // same as if (n == 5)
    { ....}
    

提交回复
热议问题