Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

In short:

class MyClass {

};

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

OR

class MyClass {

};

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
565 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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).

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).

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...