C++核心準(zhǔn)則?T.140:為所有可能重用的操作命名

T.140: Name all operations with potential for reuse
T.140:為所有可能重用的操作命名
Reason(原因)
Documentation, readability, opportunity for reuse.
文檔化,可讀性,重用的機(jī)會。
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 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.
代碼中隱藏著一個有用(在不需要區(qū)分大小寫時)的函數(shù),當(dāng)lambda表達(dá)式變大時通常會這樣。
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.
函數(shù),lambda表達(dá)式,運算符都適用。
Exception(例外)
Lambdas logically used only locally, such as an argument to?for_each?and similar control flow algorithms.
Lambda表達(dá)式邏輯上是本地使用的,例如作為一個for_each或類似的控制流算法的參數(shù)。
Lambdas as?initializers
Lambda表達(dá)式作為初始化器使用時。
Enforcement(實施建議)
(hard) flag similar lambdas
(困難)標(biāo)記類似的lambda表達(dá)式。
???
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t140-name-all-operations-with-potential-for-reuse
新書介紹
《實戰(zhàn)Python設(shè)計模式》是作者最近出版的新書,拜托多多關(guān)注!

本書利用Python 的標(biāo)準(zhǔn)GUI 工具包tkinter,通過可執(zhí)行的示例對23 個設(shè)計模式逐個進(jìn)行說明。這樣一方面可以使讀者了解真實的軟件開發(fā)工作中每個設(shè)計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進(jìn)行說明,讓讀者明白在編寫代碼時如何判斷使用設(shè)計模式的利弊,并合理運用設(shè)計模式。
對設(shè)計模式感興趣而且希望隨學(xué)隨用的讀者通過本書可以快速跨越從理解到運用的門檻;希望學(xué)習(xí)Python GUI 編程的讀者可以將本書中的示例作為設(shè)計和開發(fā)的參考;使用Python 語言進(jìn)行圖像分析、數(shù)據(jù)處理工作的讀者可以直接以本書中的示例為基礎(chǔ),迅速構(gòu)建自己的系統(tǒng)架構(gòu)。
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
