C++核心準則C.168: 將重載的運算符定義在操作對象的命名空間內

C++核心準則C.168: 將重載的運算符定義在操作對象的命名空間內

C.168: Define overloaded operators in the namespace of their operands

C.168: 將重載的運算符定義在操作對象的命名空間內

Reason(原因)

Readability. Ability for find operators using ADL. Avoiding inconsistent definition in different namespaces

可讀性。提供使用ADL發現操作符的能力。避免不同命名空間中的不一致。


ADL,Argument-dependent lookup.詳細請參照以下鏈接:

https://en.cppreference.com/w/cpp/language/adl

--譯者注

Example(示例)

<code>struct S { };
bool operator==(S, S); // OK: in the same namespace as S, and even next to S
S s;

bool x = (s == s);/<code>

This is what a default == would do, if we had such defaults.

這正是默認相等比較運算符做的事情,如果存在這麼一個默認的話。

Example(示例)

<code>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 ADL/<code>

Example, bad(反面示例)

<code>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;
}/<code>

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兩個命名空間中!s的含義不一樣。這會非常混亂。如果去掉命名空間M的定義又會增加出錯的可能。

Note(注意)

If a binary operator is defined for two types that are defined in different namespaces, you cannot follow this rule. For example:

如果為不同命名空間內的兩個不同的類型定義二目運算符,你無法遵守本準則。例如:

<code>Vec::Vector operator*(const Vec::Vector&, const Mat::Matrix&);/<code> 

This may be something best avoided.

這可能是最好狀態了。

See also(參照)

This is a special case of the rule that helper functions should be defined in the same namespace as their class.

這可以說是【幫助函數應該和它幫助的類定義在一個命名空間內】規則的特例。

Enforcement(實施建議)

  • Flag operator definitions that are not it the namespace of their operands
  • 標記沒有和操作對象定義在同一個命名空間中的運算符。


原文鏈接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c168-define-overloaded-operators-in-the-namespace-of-their-operands


覺得本文有幫助?請分享給更多人。

關注【面向對象思考】輕鬆學習每一天!

面向對象開發,面向對象思考!


分享到:


相關文章: