std::function instead of templates for predicates

c++, c++11, std-function, stl, templates

Solution

`std::function` is for runtime polymorphism. Any particular `std::function` instance could be storing a functor of any type (a type that's appropriate for the `std::function`'s signature, of course).

Standard library algorithms and such are templated on the type of their function parameters. As such, they don't need runtime polymorphism to do their job; they rely on compile-time polymorphism.

Most important of all, such algorithms don't need to force the cost of runtime polymorphism on you. If you want runtime polymorphism, you can send it a `std::function` or whatever. If you want compile-time polymorphism, you provide it a type that doesn't use polymorphic dispatch (aka: most functors or functions).

The cost of runtime polymorphism also includes the inability to inline the function call. Using a proper functor (or even function pointers, depending on how good your compiler is), the compiler can generally inline the function call if it so desires. With runtime polymorphism, not only are you paying the cost of the runtime dispatch (which may include additional parameter forwarding costs), you're also loosing important optimization opportunities.

Problem

Many standard library algorithms take predicate functions. However, the type of these predicates is an arbitrary, user-provided template parameter. Why doesn't C++11 specify that these take a specific type, like `std::function` instead? For example: ``` template< class InputIt > InputIt find_if( InputIt first, InputIt last, std::function<bool()> p ); ``` Isn't using this instead of a template as argument type not much more clean?

Original source

Related problems