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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With