C++核心準(zhǔn)則C.168: 將重載的運(yùn)算符定義在操作對(duì)象的命名空間內(nèi)

C.168: Define overloaded operators in the namespace of their operands
C.168: 將重載的運(yùn)算符定義在操作對(duì)象的命名空間內(nèi)
Reason(原因)
Readability. Ability for find operators using ADL. Avoiding inconsistent definition in different namespaces
可讀性。提供使用ADL發(fā)現(xiàn)操作符的能力。避免不同命名空間中的不一致。
ADL,Argument-dependent lookup.詳細(xì)請(qǐng)參照以下鏈接:
https://en.cppreference.com/w/cpp/language/adl
--譯者注
Example(示例)
struct S { };
bool operator==(S, S); // OK: in the same namespace as S, and even next to S
S s;
bool x = (s == s);
This is what a default?==?would do, if we had such defaults.
這正是默認(rèn)相等比較運(yùn)算符做的事情,如果存在這么一個(gè)默認(rèn)的話。
Example(示例)
namespace N {
struct S { };
bool operator==(S, S); // OK: in the same namespace as S, and even next to S
}
N::S s;
bool x = (s == s); // finds N::operator==() by ADLExample, bad(反面示例)
struct S { };
S s;
namespace N {
S::operator!(S a) { return true; }
S not_s = !s;
}
namespace M {
S::operator!(S a) { return false; }
S not_s = !s;
}
Here, the meaning of?!s?differs in?N?and?M. This can be most confusing. Remove the definition of?namespace M?and the confusion is replaced by an opportunity to make the mistake.
代碼中N和M兩個(gè)命名空間中!s的含義不一樣。這會(huì)非常混亂。如果去掉命名空間M的定義又會(huì)增加出錯(cuò)的可能。
Note(注意)
If a binary operator is defined for two types that are defined in different namespaces, you cannot follow this rule. For example:
如果為不同命名空間內(nèi)的兩個(gè)不同的類型定義二目運(yùn)算符,你無(wú)法遵守本準(zhǔn)則。例如:
Vec::Vector operator*(const Vec::Vector&, const Mat::Matrix&);
This may be something best avoided.
這可能是最好狀態(tài)了。
See also(參照)
This is a special case of the rule that?helper functions should be defined in the same namespace as their class.
這可以說(shuō)是【幫助函數(shù)應(yīng)該和它幫助的類定義在一個(gè)命名空間內(nèi)】規(guī)則的特例。
Enforcement(實(shí)施建議)
Flag operator definitions that are not it the namespace of their operands
標(biāo)記沒(méi)有和操作對(duì)象定義在同一個(gè)命名空間中的運(yùn)算符。
原文鏈接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c168-define-overloaded-operators-in-the-namespace-of-their-operands
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
