Functors are apparently more efficient since the compiler is more easily able to inline them, and they work much better with parametrization. When should you ever use a plain old function over a functor?
Asked
Active
Viewed 1,857 times
8
-
3Possible duplicate of [Why use functors over functions?](http://stackoverflow.com/questions/6451866/why-use-functors-over-functions) – Manav Dubey May 03 '17 at 22:20
-
Kind of - I read the entirety of that thread before posting, and began to wonder about the other way round. Why ever use functions over functors? – nilcit May 03 '17 at 22:24
-
Compare `v.size()` to `v.size_getter()()`. – Kerrek SB May 03 '17 at 22:35
-
1Would you mind clarifying? Also, I don't mean in place of any built in/stl functions, I mean why should I ever write a function instead of just making it a functor. – nilcit May 03 '17 at 22:37
-
1Well, as my hypothetical example shows, there are lots of things that are perfectly well handled by functions. – Kerrek SB May 03 '17 at 22:38
-
I know there are; I'm asking if functions have any actual advantages over functors or are they at most interchangable? – nilcit May 03 '17 at 22:44
-
1I think it's just the case that functions are simpler to write and use. If you don't need any of the extra features that a functor provides, write a function. To use functors, you have to define a new class for each one. – Barmar May 03 '17 at 22:49
-
3To be pedantic, how would you define a functor class without using functions? – Kerrek SB May 03 '17 at 23:06
1 Answers
17
Functions support distributed overriding. Functors do not. You must define all of the overloads of a Functor within itself; you can add new overloads of a function anywhere.
Functions support ADL (argument dependent lookup), permitting overloading in the argument-type associated namespace. Functors do not.
Function pointers are (kind of) a type-erased stateless functor that is a POD, as evidenced by how stateless lambdas convert into it. Such features (POD, stateless, type erasure) are useful.

Yakk - Adam Nevraumont
- 262,606
- 27
- 330
- 524
-
1thank you very much, this is exactly the type of answer I was looking for – nilcit May 03 '17 at 23:14
-
Function pointers aren't type erased, it actually takes a bit of work extraneous work to erase class memeber function pointers type. See here: https://godbolt.org/g/OS0u45 – 1stCLord May 04 '17 at 22:22
-
2@TheSombreroKid First, I was talking about function pointers, not member function pointers (which are a different kettle of pointers). Take `[]{}` and convert it to `void(*)()` -- that is a "kind of type erasure", in that we forget the exact operation we are doing, and just remember "we can call it with `()`. What it can kind of "erase" is highly limited. And I do mean "kind of" as opposed to "actually". Edited for clarity. – Yakk - Adam Nevraumont May 05 '17 at 01:07