c++c++03

Get the maximum sizeof at compile time c++03


I need to calculate at compile time the maximum size of four structs, to be used as an array size.

I wonder if I can do something like:

#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];

Is there a macro(that looks like MY_DESIRED_MAX_MACRO) or something else (like operators) that can do the job? Maybe #define is not the better way I think it could be done using const int but I'm not sure which is the better alternative.

[EDIT]: The purpose of this is to reserve space in static buffers to copy it.


Solution

  • Not very nice, but assuming you define

    #define MY_MAX(A,B) (((A)>(B))?(A):(B))
    

    and since all your sizeof are compile time constants (since VLAs do not exist in C++03)

    You might use

    #define MAX_SIZE_OF_STRUCT \
      MY_MAX(MY_MAX(sizeof(strcut1_type),sizeof(strcut2_type),\
             MY_MAX(sizeof(strcut3_type),sizeof(strcut4_type))
    

    (that would be preprocessor-expanded to a huge constant expression that the compiler would constant-fold)

    Of course, that trick won't scale well if you have a dozen of strcuti_type

    Maybe you could compute the sizeof some fictious union, e.g.

    union fictious_un {
     strcut1_type s1;
     strcut2_type s2; 
     strcut3_type s3; 
     strcut4_type s4;
    };
    

    then have

    #define MAX_SIZE_OF_STRUCT sizeof(union fictious_un)
    

    which scales slightly better, but does not compute exactly the same thing (e.g. because of gaps or alignment issues).

    However, you did not explain why you need this. You might need to take care of alignment issues manually elsewhere.