Lets say I have 2 struct
s:
typedef struct
{
uint8_t useThis;
uint8_t u8Byte2;
uint8_t u8Byte3;
uint8_t u8Byte4;
} tstr1
and
typedef struct
{
uint8_t u8Byte1;
uint8_t u8Byte2;
uint8_t useThis;
} tstr2
I will only need the useThis
member inside a function, but in some cases I will need to cast one struct or the other:
void someFunction()
{
someStuff();
SOMETHING MyInstance;
if(someVariable)
{
MyInstance = reinterpret_cast<tstr1*>(INFO_FROM_HARDWARE); //This line of course doesn't work
}
else
{
MyInstance = reinterpret_cast<tstr2*>(INFO_FROM_HARDWARE); //This line of course doesn't work
}
MyInstance->useThis; //Calling this memeber with no problem
moreStuff();
}
So I want to use
useThis
no matter what cast was done. How can this be done?I want to avoid
someFunction()
to be template (just to avoid this kind of things)Note tha questions like this have a kind of similar problem but the struct members have the same order
EDIT:
In RealLife these structs are way larger and have several "same named" members. Directly casting a uint8_t
as reinterpret_cast<tstr1*>(INFO_FROM_HARDWARE)->useThis
would be tedious and require several reinterpret_cast
s (althought it's a working solution for my question before this EDIT). This is why I insist on MyInstance
being "complete".
typedef struct { ... } tstr1;
dance.struct tstr1 { ... };
works just fine.MyInstance
to keep the type info after the if/else scope? That'll be hard. Otherwise you can trick it to do pretty much everything example or example - but I think this may be an XY problem.uint8_t
, would it be doable to just storeuseThis
instead ofMyInstance
pointer? or am I missing something?INFO_FROM_HARDWARE
should be some kind of union. Ideally a tagged union. More ideally astd::variant
. Less ideally astd::any
int8_t
would make a mess of a code