在编译时获取最大sizeof c ++ 03

时间:2017-04-28 13:32:19

标签: c++ 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完成的方式,但我不确定这是更好的选择。

[编辑] :目的是在静态缓冲区中保留空间以复制它。

3 个答案:

答案 0 :(得分:2)

不是很好,但假设你定义了

#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))

(那将是preprocessor - 扩展为巨大的常量表达式,编译器将constant-fold

当然,如果您有十几个strcut _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)

稍微好一点,但计算不完全相同(例如由于间隙或对齐问题)。

但是,你没有解释为什么需要这个。您可能需要在其他地方手动处理对齐问题。

答案 1 :(得分:2)

你可以不用宏来做,像这样:

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 * >));

答案 2 :(得分:2)

另一种做同样事情的方法是使用联合。然后做一个联盟的大小。

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;