具有某些公共成员的强制转换结构
假设我有 2struct秒:
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()成为模板(只是为了避免这种事情) -
请注意,像这样的问题有一种类似的问题,但结构成员的顺序相同
编辑:
在 RealLife 中,这些结构要大得多,并且有几个“同名”成员。直接投射 a uint8_tasreinterpret_cast<tstr1*>(INFO_FROM_HARDWARE)->useThis会很乏味并且需要几个reinterpret_casts(虽然这是我在此编辑之前的问题的有效解决方案)。这就是我坚持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);
}
我想避免 someFunction() 成为模板(只是为了避免这种事情)
为什么我不能将模板类的定义与其声明分开并将其放入 .cpp 文件中?
链接问题对您的用例来说不是问题,因为潜在的模板参数集是一个有限集。下一个 FAQ条目解释了如何: 使用模板的显式实例化。
- @DanielMcLaury `He's not trying to do static dispatch based on the value of the shared member` That's not what my template does either. The dispatch is based on `someVariable` like in the question. `he just wants a uniform way of accessing that member given either a tstr1 * or a tstr2 *` That's what my template does. It always accesses `useThis` and it depends on the type which member that is.