When are stateless class functors useful in place of a c style function?

前端 未结 5 494
猫巷女王i
猫巷女王i 2021-01-05 08:38

I\'ve found some good examples of functors on SO like this one, and all the convincing examples seem to use state in the class that defines operator().

5条回答
  •  遥遥无期
    2021-01-05 09:02

    One reason is run-time efficiency. If you pass a pointer to a function, the compiler has to be unusually clever to produce code for that function inline. Passing an object that defines operator() makes it much easier for the compiler to produce the code inline. Especially for something like sorting, this can increase speed quite substantially.

    In C++11, another reason to use a class is for convenience -- you can use a lambda expression to define the class.

提交回复
热议问题