After reading this answer, I made some tests and I came up with the following code:
#include <iostream>
template <typename T>
class Test {
int val{42};
friend std::ostream & operator << (std::ostream & flux, Test const & instance) {
return flux << Test<char>{}.val;
}
};
int main() {
std::cout << Test<int>{};
return 0;
}
Using Test<int>
in main()
, I thought that operator<<
couldn't access Test<char>{}.val
. But to my surprise, GCC compiled fine.
Then, I tested with Clang and Visual Studio, and both gave me a private member error, as expected (see GCC/Clang demo).
Which compiler is right?
Also, I'm wondering in which case one would need the extrovert version mentioned in the link? Or private access to Test<U>
from within operator<<
of Test<T>
(when T
!= U
)? Do you have any practical examples?