M
mlimber
Victor said:mlimber said:andrew said:Is this code below valid C++? I'd like to use this construct but I'm
not sure if it'll be portable.
struct foo
{
char x[128];
};
struct bar
{
char sameSizeAsFooX[ sizeof ((foo *)0)->x ];
};
Though that seems to work, for the sake of clarity, I would do it
differently. At worst, something like this:
char sameSizeAsFooX[ sizeof foo().x ];
This requires 'foo' to be default-constructible, which is not always
possible.
Better, IMHO, would be:
struct foo
{
enum { SIZE = 128 };
char x[SIZE];
};
struct bar
{
char sameSizeAsFooX[ foo::SIZE ];
};
I agree. The problem is that editing 'foo' to introduce 'SIZE' is not
always possible. Besides, the trick with (0)-> can be used in templates
whereas you cannot expect every class that has 'x' member for which you
want to create a corresponding 'sameSizeAs..' also contains 'SIZE'...
Agreed on all counts. If it is possible, however, it is better to write
more readable (less obscure) code. As Kernighan's Law states:
"Debugging is twice as hard as writing the program, so if you write the
program as cleverly as you can, by definition, you won't be clever
enough to debug it."
Cheers! --M