C++核心准则C.168: 将重载的运算符定义在操作对象的命名空间内

面向对象思考

共 1928字,需浏览 4分钟

 ·

2020-03-05 23:22

7e13b714eef9e1edddfd5fc824bc4f76.webp

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(示例)

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

Example, 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两个命名空间中!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(实施建议)

  • 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




觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!


浏览 18
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报