指向两种不同结构的指针

Rei*_*ugh 2 c++ pointers structure

我有三个结构header,dataAdataB.在header将确定将要使用的结构.在dataAdataB具有几乎相同的结构(比方说):

struct dataA
{
    int   intValue;
    char  reserved1[8];
    float floatValue;
    char  reserved2[4];
    short shortValue;
};

struct dataA
{
    int   intValue;
    short shortValue;
    char  reserved[2];
    float floatValue;
};
Run Code Online (Sandbox Code Playgroud)

我想打印它像:

sprintf(outStr, "%i, %f, %s", p->intValue, p->floatValue, p->shortValue);
Run Code Online (Sandbox Code Playgroud)

- 要么 -

sprintf(outStr, "%i, %f, %s", p.intValue, p.floatValue, p.shortValue);
Run Code Online (Sandbox Code Playgroud)

我该如何申报p?(注意:这两个dataAdataB具有大的结构,但几乎是相同的数据,除了那些被保留.值)

我在想这样的事情:

void * p;

if (header->type==1)
   p = (dataA*)(pData);
else if (header->type==2)
   p = (dataB*)(pData);

// print all data here
Run Code Online (Sandbox Code Playgroud)

注意:pData是一个指向我将要读取的(原始)数据的指针.我只需要那些非保留值并忽略保留值.

Jam*_*lis 7

将打印逻辑移动到功能模板中:

template <typename T>
int print_data(char* const str, std::size_t const len, T const* const p)
{
    return std::snprintf(
        str, len,
        "%i, %f, %s",
        p->intValue, p->floatValue, p->shortValue);
}
Run Code Online (Sandbox Code Playgroud)

然后从切换逻辑中调用此函数:

if (header->type==1)
    print_data(str, len, static_cast<dataA const*>(pData));
else if (header->type==2)
    print_data(str, len, static_cast<dataB const*>(pData));
Run Code Online (Sandbox Code Playgroud)

如果您打算使用std::snprintf,最好将static_asserts 添加到print_data函数模板中,以确保数据成员T的类型是您期望的类型,只是为了确定.

请注意,如果您的平台具有严格的对齐要求,并且pData无法保证为所有目标类型正确对齐指向的数据,则需要将具有字节副本的强制转换替换为适当对齐的缓冲区.