Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it still advisable to pass functors to STL instead of functions?

Tags:

c++

stl

In Effective STL, Scott Meyers back in 2001 advises:

Item 46: Consider function objects instead of functions as algorithm parameters

In said chapter, he proceeds to explain that inline operator() can get inlined into the algorithm's body, but passing a function generally can`t. This is because we are passing a function pointer actually.

In support of that I seem to remember that if a function's address is ever taken, the function can't be inlined.

So two questions here. Firstly, is this still true with C++14?

If yes:

  • Why is there no mechanism to do this automatically (motivation: declaring a functor is a lot less straightforward and readable, than declaring a function).
  • A lambda without capture is convertible to function pointer, while a capturing lambda can only be passed as a functor. Does this mean we need to capture something only for the sake of the stated optimization?
like image 421
Vorac Avatar asked Feb 04 '15 11:02

Vorac


1 Answers

Is this still true with C++14?

Depends on whether the compiler can inline the whole algorithm. If it can, then it can probably also inline the function call. If not, then the function probably can't be inlined, because the algorithm in that case is instantiated using a function pointer type and so must be able to handle all function pointers of that type.

For instance, g++ can inline a simple algorithm like std::transform but not std::sort.

A lambda without capture is convertible to function pointer, while a capturing lambda can only be passed as a functor. Does this mean we need to capture something only for the sake of stated at top optimization?

No. A lambda without capture is still a functor; the algorithm is instantiated using the closure type (the type of the lambda) rather than the function pointer type.

like image 167
T.C. Avatar answered Oct 13 '22 01:10

T.C.