前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.168: 将重载的运算符定义在操作对象的命名空间内

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

作者头像
面向对象思考
发布2020-03-25 16:59:59
7890
发布2020-03-25 16:59:59
举报

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

代码语言:javascript
复制
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(示例)

代码语言:javascript
复制
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(反面示例)
代码语言:javascript
复制
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:

如果为不同命名空间内的两个不同的类型定义二目运算符,你无法遵守本准则。例如:

代码语言:javascript
复制
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


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

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

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reason(原因)
    • Example, bad(反面示例)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档