Iva*_*van 4 c++ struct casting reinterpret-cast c++11
假设我有 2struct
秒:
typedef struct
{
uint8_t useThis;
uint8_t u8Byte2;
uint8_t u8Byte3;
uint8_t u8Byte4;
} tstr1
Run Code Online (Sandbox Code Playgroud)
和
typedef struct
{
uint8_t u8Byte1;
uint8_t u8Byte2;
uint8_t useThis;
} tstr2
Run Code Online (Sandbox Code Playgroud)
我只需要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();
}
Run Code Online (Sandbox Code Playgroud)
编辑:
在 RealLife 中,这些结构要大得多,并且有几个“同名”成员。直接投射 a uint8_t
asreinterpret_cast<tstr1*>(INFO_FROM_HARDWARE)->useThis
会很乏味并且需要几个reinterpret_cast
s(虽然这是我在此编辑之前的问题的有效解决方案)。这就是我坚持MyInstance
“完整”的原因。
这是模板的用途:
template<class tstr>
std::uint8_t
do_something(std::uint8_t* INFO_FROM_HARDWARE)
{
tstr MyInstance;
std::memcpy(&MyInstance, INFO_FROM_HARDWARE, sizeof MyInstance);
MyInstance.useThis; //Calling this memeber with no problem
// access MyInstance within the template
}
// usage
if(someVariable)
{
do_something<tstr1>(INFO_FROM_HARDWARE);
}
else
{
do_something<tstr2>(INFO_FROM_HARDWARE);
}
Run Code Online (Sandbox Code Playgroud)
我想避免 someFunction() 成为模板(只是为了避免这种事情)
为什么我不能将模板类的定义与其声明分开并将其放入 .cpp 文件中?
链接问题对您的用例来说不是问题,因为潜在的模板参数集是一个有限集。下一个 FAQ条目解释了如何: 使用模板的显式实例化。