Is is possible to overload a reference cast in C++?
I've got code I can't touch in the format:
void someMethod(Parent& parentReference, ...){
...
Child& child = static_cast<Child&>(parentReference);
(The class Child inherits directly and publicly from the class Parent)
I'd like to adjust the behavior of this cast - I can modify the class Child.
I've tried overloading the cast operator like so:
Parent::operator Child&(){
...
But this method never gets called.
I'm starting to wonder if this is even possible?
EDIT
Per R Sahu, I'm close to this scenario:
https://timsong-cpp.github.io/cppwp/n3337/expr.static.cast#2
struct B { };
struct D : public B { };
D d;
B &br = d;
static_cast<D&>(br); // produces lvalue to the original d object
Except that instead of simply assigning B &br = d;
, br
comes into the method as an argument, and is previously sent over the network (as NML).
This would be the scenario:
struct B { };
struct D : public B {
int a;
int b
};
D d;
d.a = x;
d.b = y;
server.send(d);
...
client.receive(msg);
receive(B& msg){
D& msgD = static_cast<D&>(msg);
}
msgD.x
and msgD.y
come over the wire and are reconstructed properly. However, I would like to change the way they are reconstructed, without modifying the receive
method. Is this possible?