前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则​T.140:为所有可能重用的操作命名

C++核心准则​T.140:为所有可能重用的操作命名

作者头像
面向对象思考
发布2020-10-10 09:54:48
3950
发布2020-10-10 09:54:48
举报

T.140: Name all operations with potential for reuse

T.140:为所有可能重用的操作命名

Reason(原因)

Documentation, readability, opportunity for reuse.

文档化,可读性,重用的机会。

Example(示例)

代码语言:javascript
复制
struct Rec {
    string name;
    string addr;
    int id;         // unique identifier
};

bool same(const Rec& a, const Rec& b)
{
    return a.id == b.id;
}

vector<Rec*> find_id(const string& name);    // find all records for "name"

auto x = find_if(vr.begin(), vr.end(),
    [&](Rec& r) {
        if (r.name.size() != n.size()) return false; // name to compare to is in n
        for (int i = 0; i < r.name.size(); ++i)
            if (tolower(r.name[i]) != tolower(n[i])) return false;
        return true;
    }
);

There is a useful function lurking here (case insensitive string comparison), as there often is when lambda arguments get large.

代码中隐藏着一个有用(在不需要区分大小写时)的函数,当lambda表达式变大时通常会这样。

代码语言:javascript
复制
bool compare_insensitive(const string& a, const string& b)
{
    if (a.size() != b.size()) return false;
    for (int i = 0; i < a.size(); ++i) if (tolower(a[i]) != tolower(b[i])) return false;
    return true;
}

auto x = find_if(vr.begin(), vr.end(),
    [&](Rec& r) { compare_insensitive(r.name, n); }
);

Or maybe (if you prefer to avoid the implicit name binding to n):

或者可以这样(如果你更希望避免n上的隐式名称绑定):

代码语言:javascript
复制
auto cmp_to_n = [&n](const string& a) { return compare_insensitive(a, n); };

auto x = find_if(vr.begin(), vr.end(),
    [](const Rec& r) { return cmp_to_n(r.name); }
);
Note(注意)

whether functions, lambdas, or operators.

函数,lambda表达式,运算符都适用。

Exception(例外)

  • Lambdas logically used only locally, such as an argument to for_each and similar control flow algorithms. Lambda表达式逻辑上是本地使用的,例如作为一个for_each或类似的控制流算法的参数。
  • Lambdas as initializers Lambda表达式作为初始化器使用时。
Enforcement(实施建议)
  • (hard) flag similar lambdas
  • (困难)标记类似的lambda表达式。
  • ???

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t140-name-all-operations-with-potential-for-reuse

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Note(注意)
  • Enforcement(实施建议)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档