C++ allows for overloading type casts by creating an operator T() where T is the type we want to cast to.
Now, how does this feature play together with references? For example:
struct Y{ int i; }; struct X{ Y y; operator Y() const { return y; } }; Here, we can cast an X to Y which will simply return the contained Y. But what if we want to make a cast to an Y reference. For example, C++ allows us to do this:
struct X{ Y y; operator Y&(){ return y; } operator const Y&() const { return y; } }; Now, we can cast an X to a Y reference or a const reference (which also works for a const X).
Is there any difference in the semantics of the first and the second example? What is the best way if I want to allow casting to a reference?
I could imagine that even if I write operator T() without any &, C++ might allow that the cast returns a result by reference (i.e., it might somehow add implicit operator T&() methods when I specify operator T()).
For example, I want the following code to work:
int main(){ X x; Y& y = x; // y now references the y inside x y.i = 5; std::cout << x.y.i << std::endl; // Should print 5 now } What is the most simple way to achieve this?
operator T()(without&) imply that the cast always returns aTby value? Or are there some rules thatTmay be returned as reference in some cases? I have tried to clarify the question.