Skip to content

Instantly share code, notes, and snippets.

@IMelker
Created July 13, 2020 11:28
Show Gist options
  • Save IMelker/b818c0a529c017ced138844231a7e603 to your computer and use it in GitHub Desktop.
Save IMelker/b818c0a529c017ced138844231a7e603 to your computer and use it in GitHub Desktop.
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