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

时间:2022-07-26
本文章向大家介绍C++核心准则​T.140:为所有可能重用的操作命名,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

T.140: Name all operations with potential for reuse

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

Reason(原因)

Documentation, readability, opportunity for reuse.

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

Example(示例)

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表达式变大时通常会这样。

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上的隐式名称绑定):

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