Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
254 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...