具有某些公共成员的强制转换结构

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)
  • 所以我想使用useThis无论做了什么演员。如何才能做到这一点?

  • 我想避免someFunction()成为模板(只是为了避免这种事情

  • 请注意,像这样的问题有一种类似的问题,但结构成员的顺序相同

编辑:

在 RealLife 中,这些结构要大得多,并且有几个“同名”成员。直接投射 a uint8_tasreinterpret_cast<tstr1*>(INFO_FROM_HARDWARE)->useThis会很乏味并且需要几个reinterpret_casts(虽然这是我在此编辑之前的问题的有效解决方案)。这就是我坚持MyInstance“完整”的原因。

eer*_*ika 5

这是模板的用途:

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条目解释了如何: 使用模板的显式实例化。

  • @DanielMcLaury`他并没有尝试根据共享成员的值进行静态调度`这也不是我的模板所做的。调度基于问题中的“someVariable”。`他只是想要一种统一的方式来访问给定 tstr1 * 或 tstr2 * 的成员` 这就是我的模板所做的。它总是访问“useThis”,这取决于该成员的类型。 (2认同)