前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则F.50:不愿意使用函数时使用lambda表达式

C++核心准则F.50:不愿意使用函数时使用lambda表达式

作者头像
面向对象思考
发布2020-03-25 15:37:40
5400
发布2020-03-25 15:37:40
举报

F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)

F.50:在不愿意使用函数时使用lambda表达式(例如读取局部变量,访问局部函数)

Reason(原因)

Functions can't capture local variables or be defined at local scope; if you need those things, prefer a lambda where possible, and a handwritten function object where not. On the other hand, lambdas and function objects don't overload; if you need to overload, prefer a function (the workarounds to make lambdas overload are ornate). If either will work, prefer writing a function; use the simplest tool necessary.

函数无法使用函数体外部的局部变量,也不能定义在局部作用域;如果你需要这方面功能,如果可能的话使用lambda表达式是较好的选择,否则需要自己实现函数对象。另一方面,lambda表达式和函数对象无法实现重载;如果你需要重载,函数更合适(通过折腾让lambda表达式重载的方法太高级)。如果两种方式都可用,用函数更好;使用满足需要的,最简单的工具。

Example(示例)
// writing a function that should only take an int or a string
// -- overloading is natural
void f(int);
void f(const string&);

// writing a function object that needs to capture local state and appear
// at statement or expression scope -- a lambda is natural
vector<work> v = lots_of_work();
for (int tasknum = 0; tasknum < max; ++tasknum) {
    pool.run([=, &v]{
        /*
        ...
        ... process 1 / max - th of v, the tasknum - th chunk
        ...
        */
    });
}
pool.join();

Exception(例外)

Generic lambdas offer a concise way to write function templates and so can be useful even when a normal function template would do equally well with a little more syntax. This advantage will probably disappear in the future once all functions gain the ability to have Concept parameters.

通常的lambda表达式提供一种实现函数模板的简明方式,因此很有用;一个普通的函数模板想要做相同的事情甚至需要稍微复杂的语法。但是将来一旦所有的函数都可以拥有概念参数,这个优势将来很可能会消失。

译者注:Concept是C++20将会导入的新特性。

Enforcement(实施建议)
  • Warn on use of a named non-generic lambda (e.g., auto x = [](int i){ /*...*/; };) that captures nothing and appears at global scope. Write an ordinary function instead. 在使用了一个没有获取任何变量而且存在于全局作用域的、命名的非普通lambda表达式(例如auto x=[](int){/*...*/};)时报警。

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

关注【面向对象思考】,每天前进一小步

有任何疑问,欢迎留言提问或讨论


面向对象设计,面向对象编程,面向对象思考!

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.50: Use a lambda when a function won't do (to capture local variables, or to write a local function)
    • Reason(原因)
      • Example(示例)
        • Exception(例外)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档