C++核心准则T.40: 使用函数对象向算法传递操作_函数对象

T.40: Use function objects to pass operations to algorithms

T.40: 使用函数对象向算法传递操作

Reason(原因)

Function objects can carry more information through an interface than a "plain" pointer to function. In general, passing function objects gives better performance than passing pointers to functions.

相比普通的函数指针,函数对象可以通过接口传递更多的信息。相比传递函数指针,传递函数对象通常可以提供更好的性能。

Example (using TS concepts)(示例(使用TS概念))

bool greater(double x, double y) { return x > y; }
sort(v, greater); // pointer to function: potentially slow
sort(v, [](double x, double y) { return x > y; }); // function object
sort(v, std::greater<>); // function object

bool greater_than_7(double x) { return x > 7; }
auto x = find_if(v, greater_than_7); // pointer to function: inflexible
auto y = find_if(v, [](double x) { return x > 7; }); // function object: carries the needed data
auto z = find_if(v, Greater_than<double>(7)); // function object: carries the needed data

You can, of course, generalize those functions using auto or (when and where available) concepts. For example:

你当然可以使用auto或(如果可以)概念生成这些函数。

auto y1 = find_if(v, [](Ordered x) { return x > 7; }); // require an ordered type
auto z1 = find_if(v, [](auto x) { return x > 7; }); // hope that the type has a >

Note(注意)

Lambdas generate function objects.

Lambda表达式生成的是函数对象

Note(注意)

The performance argument depends on compiler and optimizer technology.

性能指标由编译器和优化技术决定。

Enforcement(实施建议)

  • Flag pointer to function template arguments.
  • 标志函数指针类型的模板参数。
  • Flag pointers to functions passed as arguments to a template (risk of false positives).
  • 标记传递给模板参数的函数指针(误检出的风险)

原文链接

​https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t40-use-function-objects-to-pass-operations-to-algorithms​

新书介绍

​《实战Python设计模式》​​是作者最近出版的新书,拜托多多关注!

C++核心准则T.40: 使用函数对象向算法传递操作_设计模式_02

本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。


觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

C++核心准则T.40: 使用函数对象向算法传递操作_设计模式_03