jeudi 29 janvier 2015

Is there a way to simulate upcasting by reference

So, I have something along the lines of these structs:



struct Generic {}
struct Specific : Generic {}


At some point I have the the need to downcast, ie:



Specific s = (Specific) GetGenericData();


This is a problem because I get error messages stating that no user-defined cast was available.


I can change the code to be:



Specific s = (*(Specific *)&GetGenericData())


or using reinterpret_cast, it would be:



Specific s = *reinterpret_cast<Specific *>(&GetGenericData());


But, is there a way to make this cleaner? Perhaps using a macro or template?


I looked at this post C++ covariant templates, and I think it has some similarities, but not sure how to rewrite it for my case. I really don't want to define things as SmartPtr. I would rather keep things as the objects they are.


Aucun commentaire:

Enregistrer un commentaire