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?
I believe Clang/VS are using the correct behavior, because if you create a new instance (as in your example) instead of using the friended instance from the parameters I believe it resets the access to be as if it's from outside.
As for the extra question, I can't think of a practical example the extrovert, but I imagine it's there for the same reason as many things in C++, to let you do it that way if you want to. Maybe use it to convert from one type to another? not sure, sorry^^;
PS sorry for the original confusion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.