[英]Get the maximum sizeof at compile time c++03
我需要在編譯時計算四個結構的最大大小,以用作數組大小。
我想知道我是否可以做類似的事情:
#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
完成的方式,但是我不確定wich是更好的選擇。
[編輯] :此操作的目的是在靜態緩沖區中保留空間以進行復制。
不太好,但是假設您定義
#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
,那么該技巧將無法很好地擴展
也許您可以計算一些虛擬union
的sizeof
,例如
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.