Size of a class instance at compile time
Daniel Keep
daniel.keep+lists at gmail.com
Sun Jan 14 05:50:07 PST 2007
Frits van Bommel wrote:
> Frits van Bommel wrote:
>
>> [1]: e.g. I haven't tested using anything with explicit align(N)
>> declarations, not sure what happens there (would .alignof be adjusted?).
>
>
> Yep, definitely breaks there. But I did find a much more elegant
> implementation that *does* work in that case (as well as in normal cases):
>
> -----
> template InstanceSize(T)
> {
> const InstanceSize =
> T.tupleof[$-1].offsetof + T.tupleof[$-1].sizeof;
> }
> ------
Just wondering; do we even need to worry about align(N) attributes?
AFAIK, that only applies to structures, and we can get the size of those
using sizeof since they're value types.
http://digitalmars.com/d/attribute.html#align -- says down the bottom of
that heading that it only applies to structs and struct members.
> _Way_ shorter, and always provides the correct answer under two simple
> assumptions:
> 1) The last non-static member is also last in the layout
> 2) There's no padding at the end.
>
> Assumption (1) is pretty likely to be broken if and when member
> reordering is implemented, though.
I just knocked up a slightly more robust version that should
*theoretically* still work even if the members are moved around. It
basically just does the same thing yours does, but it runs over the
whole tuple, and passes out the largest value it finds.
Obviously, it doesn't help for the above two points, but Walter seems to
like stuff at the start of the block, not trailing off the end. Plus,
when would a class require padding?
-- Daniel
template InstanceSize(T)
{
const InstanceSize = InstanceSizeImpl!(T, 0);
}
template InstanceSizeImpl(T, size_t i)
{
static if( i < T.tupleof.length )
const InstanceSizeImpl = Max!(
T.tupleof[i].offsetof + T.tupleof[i].sizeof,
InstanceSizeImpl!(T, i+1));
else
const InstanceSizeImpl = 0u;
}
template Max(size_t a, size_t b)
{
static if( a > b )
const Max = a;
else
const Max = b;
}
More information about the Digitalmars-d-learn
mailing list