C.168: Define overloaded operators in the namespace of their operands
C.168: 将重载的运算符定义在操作对象的命名空间内
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(示例)
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.
这正是默认相等比较运算符做的事情,如果存在这么一个默认的话。
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 ADL
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两个命名空间中!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:
如果为不同命名空间内的两个不同的类型定义二目运算符,你无法遵守本准则。例如:
Vec::Vector operator*(const Vec::Vector&, const Mat::Matrix&);
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(实施建议)
原文链接:
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c168-define-overloaded-operators-in-the-namespace-of-their-operands
觉得本文有帮助?请分享给更多人。
关注【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!