Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hidden friend idiom
namespace N {
class MyType {
Mytype& operator+=(const MyType&);
void print(std::ostream&);
void swap(MyType&) noexcept;
friend MyType operator+(MyType a, const MyType& b) {
a += b;
return a;
}
friend std::ostream& operator<<(std::ostream& os, const MyType& b) {
b.print(os);
return os;
}
friend void swap(MyType& a, MyType& b) noexcept {
a.swap(b);
}
};
} //namespace N
void test(N::MyType& t) {
t + t; // considers N::operator+
std::cout << t; // considers N::operator<<
swap(t, t); // considers N::swap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment