What are C++ functors and their uses?

后端 未结 14 1546
花落未央
花落未央 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 05:06

    Name "functor" has been traditionaly used in category theory long before C++ appeared on the scene. This has nothing to do with C++ concept of functor. It's better to use name function object instead of what we call "functor" in C++. This is how other programming languages call similar constructs.

    Used instead of plain function:

    Features:

    • Function object may have state
    • Function object fits into OOP (it behaves like every other object).

    Cons:

    • Brings more complexity to the program.

    Used instead of function pointer:

    Features:

    • Function object often may be inlined

    Cons:

    • Function object can not be swapped with other function object type during runtime (at least unless it extends some base class, which therefore gives some overhead)

    Used instead of virtual function:

    Features:

    • Function object (non-virtual) doesn't require vtable and runtime dispatching, thus it is more efficient in most cases

    Cons:

    • Function object can not be swapped with other function object type during runtime (at least unless it extends some base class, which therefore gives some overhead)

提交回复
热议问题