Quick Q: When should I use std::function vs. make my function a template? -- StackOverflow

To accept a functor as a parameter, when should you:

  • accept a std::function, which adds an indirection, vs.
  • make your function a template<class Func> and accept a Func, which can bind directly to whatever is passed?

std::function vs template

Thanks to C++11 we received the std::function family of functor wrappers. Unfortunately, I keep hearing [...] that they are horribly slow. [... Is the right recommendation] that functions can be used as de facto standard of passing functors, and in places where high performance is expected templates should be used?

Add a Comment

Comments are closed.

Comments (3)

1 0

Bjarne Stroustrup said on Feb 21, 2013 09:30 AM:

How slow is horribly slow? How many time do you have to call a function for it to matter?
0 0

Johan Lundberg said on Feb 24, 2013 01:36 AM:

Bjarne, in *addition* to your comment: The posted example did not actually observe any of the resulting calculations. Fixing that it's clear that there's absolutely no 'horrible penalty' (at least not with clang or visual studio. gcc is a bit behind): http://stackoverflow.com/a/15045156/1149664 .
0 0

Bjarne Stroustrup said on Feb 24, 2013 08:45 AM:

Yes. My implied general point is that if you want comment about efficiency, you need to measure and to have an idea of the frequency and importance of the code you consider efficient or inefficient.