非成员运算符重载应该放在哪里?

2022-01-14 00:00:00 namespaces operator-overloading c++

我想为我的班级重载 operator<<.我应该将此重载定义添加到 std 命名空间吗?(因为 ostream 运算符<<std 命名空间的一部分)还是应该将它留在全局命名空间中?

I want to overload operator<< for my class. Should I add this overloaded definition to the std namespace? (since the ostream operator<< is part of the std namespace) Or should I just leave it in the global namespace?

简而言之:

class MyClass {

};

namespace std {
    ostream& operator<< ( ostream& Ostr, const MyClass& MyType ) {}
}

class MyClass {

};

std::ostream& operator<< ( std::ostream& Ostr, const MyClass& MyType ) {}

哪个更合适,为什么?提前感谢您的回复.

Which is more appropriate and why? Thanks in advance for your responses.

推荐答案

您应该将运算符重载放在与您的类相同的命名空间中.

You should put the operator overload in the same namespace as your class.

这将允许在重载解析期间使用依赖于参数的查找找到运算符(实际上,由于 ostream 在命名空间 std 中,重载重载也会如果你把它放在命名空间 std 中就可以找到,但没有理由这样做).

This will allow the operator to be found during overload resolution using argument-dependent lookup (well, actually, since ostream is in namespace std, the overload overload would also be found if you put it in namespace std, but there is no reason to do that).

从良好设计实践的角度来看,运算符重载更多是类接口的一部分,而不是 ostream 的接口,因此它与您的类属于同一命名空间(另请参阅Herb Sutter 的 命名空间和接口原则??).

From the point of view of good design practices, the operator overload is more a part of your class's interface than the interface of ostream, so it belongs in the same namespace as your class (see also Herb Sutter's Namespaces and the Interface Principle).

从编写符合标准的可移植代码的角度来看,您不能将运算符重载放入命名空间std.虽然您可以将用户定义实体的模板特化添加到命名空间 std,但您不能添加额外的函数重载.

From the point of view of writing standards-compliant and portable code, you can't put the operator overload into namespace std. While you can add template specializations for user-defined entities to namespace std, you can't add additional function overloads.

相关文章