【发布时间】:2021-09-07 23:26:11
【问题描述】:
假设我有 2 个structs:
typedef struct
{
uint8_t useThis;
uint8_t u8Byte2;
uint8_t u8Byte3;
uint8_t u8Byte4;
} tstr1
和
typedef struct
{
uint8_t u8Byte1;
uint8_t u8Byte2;
uint8_t useThis;
} tstr2
我将仅在函数中需要 useThis 成员,但在某些情况下,我需要转换一个结构或另一个:
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();
}
-
所以我想使用
useThis,不管演员是什么。如何做到这一点? -
我想避免
someFunction()成为模板(只是为了避免 this kind of things) -
注意像this 这样的问题也有类似的问题,但结构成员的顺序相同
编辑:
在 RealLife 中,这些结构体要大得多,并且有几个“同名”成员。直接将uint8_t 转换为reinterpret_cast<tstr1*>(INFO_FROM_HARDWARE)->useThis 会很乏味,并且需要几个reinterpret_casts(尽管这是我在编辑之前的问题的有效解决方案)。这就是为什么我坚持MyInstance 是“完整的”。
【问题讨论】:
-
这并没有解决问题,但在 C++ 中你不必跳
typedef struct { ... } tstr1;舞蹈。struct tstr1 { ... };工作得很好。 -
似乎只是一个
uint8_t,是否可以只存储useThis而不是MyInstance指针?还是我错过了什么? -
INFO_FROM_HARDWARE应该是某种联合。理想情况下是带标签的工会。更理想的是std::variant。不太理想的是std::any -
@ben10 这是一个小例子,IRL 有几个成员,INFO_FROM_HARDWARE 很大,直接使用
int8_t会乱码
标签: c++ c++11 struct casting reinterpret-cast