C++核心准则F.50:不愿意使用函数时使用lambda表达式
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++核心准则F.50:不愿意使用函数时使用lambda表达式,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2477字,纯文字阅读大概需要4分钟。
内容图文
![C++核心准则F.50:不愿意使用函数时使用lambda表达式](/upload/InfoBanner/zyjiaocheng/646/bd76e1afcb434c8997fe0b7218a1d4a2.jpg)
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){/*...*/};)时报警。
觉得本文有帮助?欢迎点赞并分享给更多的人!
阅读更多更新文章,请关注微信公众号【面向对象思考】
面向对象思考 博客专家 发布了407 篇原创文章 · 获赞 587 · 访问量 27万+ 他的留言板 关注内容总结
以上是互联网集市为您收集整理的C++核心准则F.50:不愿意使用函数时使用lambda表达式全部内容,希望文章能够帮你解决C++核心准则F.50:不愿意使用函数时使用lambda表达式所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。