我有三个结构header
、dataA
和dataB
。 header
将决定将要使用的结构。 dataA
和 dataB
具有几乎相同的结构(比方说):
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;
};
我想像这样打印它:
sprintf(outStr, "%i, %f, %s", p->intValue, p->floatValue, p->shortValue);
-- 或者 --
sprintf(outStr, "%i, %f, %s", p.intValue, p.floatValue, p.shortValue);
如何声明p
? (注意: dataA
和 dataB
都有很大的结构,但数据几乎相同,除了那些保留的 值。)
我是这样想的:
void * p;
if (header->type==1)
p = (dataA*)(pData);
else if (header->type==2)
p = (dataB*)(pData);
// print all data here
注意: 这里的 pData
是指向我将读取的(原始)数据的指针。我只需要那些非保留值,而忽略保留值。
最佳答案
将打印逻辑移动到函数模板中:
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);
}
然后从你的切换逻辑中调用这个函数:
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));
如果您计划使用 std::snprintf
,最好将 static_assert
添加到 print_data
函数模板以确保 T
的数据成员类型是您期望的类型,只是为了确定。
请注意,如果您的平台有严格的对齐要求,并且不能保证 pData
指向的数据对于您的所有目标类型都正确对齐,您将需要用一个拷贝替换强制转换字节放入适当对齐的缓冲区。
关于c++ - 指向两个不同结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11337678/