我需要在编译时计算四个结构体的最大大小,以用作数组大小。
我想知道我是否可以做这样的事情:
#define MAX_SIZE_OF_STRUCTS MY_DESIRED_MAX_MACRO (sizeof(strcut1_type),
sizeof(strcut2_type),
sizeof(strcut3_type),
sizeof(strcut4_type))
int my_array[MAX_SIZE_OF_STRUCTS];
是否有宏(看起来像
MY_DESIRED_MAX_MACRO
)或其他东西(如运算符)可以完成这项工作?
也许 #define
不是更好的方法,我认为可以使用 const int
来完成,但我不确定哪个是更好的选择。
[编辑]:这样做的目的是在静态缓冲区中保留空间来复制它。
不太好,但假设你定义了
#define MY_MAX(A,B) (((A)>(B))?(A):(B))
并且由于所有
sizeof
都是编译时常量(因为 VLA 在 C++03 中不存在)
你可能会使用
#define MAX_SIZE_OF_STRUCT \
MY_MAX(MY_MAX(sizeof(strcut1_type),sizeof(strcut2_type),\
MY_MAX(sizeof(strcut3_type),sizeof(strcut4_type))
(这将是预处理器扩展为一个巨大的常量表达式,编译器将常量折叠)
当然,如果你有十几个
strcut
i_type
,这个技巧就无法很好地扩展
也许你可以计算
sizeof
一些虚构的 union
,例如
union fictious_un {
strcut1_type s1;
strcut2_type s2;
strcut3_type s3;
strcut4_type s4;
};
然后有
#define MAX_SIZE_OF_STRUCT sizeof(union fictious_un)
其缩放效果稍好,但计算的结果并不完全相同(例如,由于间隙或对齐问题)。
但是,您没有解释为什么需要这个。您可能需要在其他地方手动处理对齐问题。
你可以不用宏来做到这一点,像这样:
template< typename T1, typename T2, typename T3, typename T4 > class
largest_of4
{
union inner
{
char v1[sizeof(T1)];
char v2[sizeof(T2)];
char v3[sizeof(T3)];
char v4[sizeof(T4)];
};
char dummy[sizeof(inner)];
};
assert(19 == sizeof(largest_of4< char, char[19], double, void * >));
做同样事情的另一种方法是通过工会。然后做一个联合的大小。
union thirteen {
a strcut1_type;
b strcut2_type;
c strcut3_type;
d strcut4_type;
};
int tag; // An integer to describe which on is active.
union thirteen myunion;
为了清晰起见,通常将标签放在结构体中。
struct mystruct {
int tag;
union thirteen myunion;
};
struct mystuct myvalues;