前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则T.40: 使用函数对象向算法传递操作

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

作者头像
面向对象思考
发布2020-09-10 10:26:37
5140
发布2020-09-10 10:26:37
举报

大连 高新园区

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概念))

代码语言:javascript
复制
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或(如果可以)概念生成这些函数。

代码语言:javascript
复制
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设计模式》是作者最近出版的新书,拜托多多关注!

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

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-09-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 大连 高新园区
  • T.40: Use function objects to pass operations to algorithms
  • Reason(原因)
    • Note(注意)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档