std :: function代替谓词的模板 [英] std::function instead of templates for predicates

查看:139
本文介绍了std :: function代替谓词的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多标准库算法使用谓词函数。但是,这些谓词的类型是任意的,用户提供的模板参数。为什么C ++ 11不指定这些具体类型,如 std :: function ?例如:

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?

推荐答案

std :: function 是用于运行时的多态性。任何特定的 std :: function 实例可以存储任何类型的函子(一种适用于 std :: function '的签名,当然)。

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.

最重要的是,这些算法不需要强制运行时多态性的 cost 。如果你想要运行时多态性,你可以发送一个 std :: function 或任何。如果你想要编译时多态性,你可以提供一个不使用多态分派(aka:大多数函子或函数)的类型。

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.

这篇关于std :: function代替谓词的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆