Fields size property

Ali Çehreli acehreli at yahoo.com
Thu Nov 10 19:27:16 PST 2011


On 11/10/2011 05:44 PM, Andrej Mitrovic wrote:
> .sizeof on a struct works nicely since it's a POD, but this can't work
> on classes since it just returns the pointer size.
>
> I don't know whether this is useful all that much, but I'm curious how
> large my classes are. Anyway, since I couldn't find anything in Phobos
> I've got this working:
>
> import std.traits;
>
> auto getFieldsSizeOf(T)() {
>      size_t result;
>      foreach (type; RepresentationTypeTuple!Foo) {
>          result += type.sizeof;
>      }
>      return result;
> }
>
> template fieldsSizeOf(T) {
>      enum size_t fieldsSizeOf = getFieldsSizeOf!T();
> }
>
> class Foo { int x, y; }
> static assert(fieldsSizeOf!Foo == 8);
> void main() { }

This is the standard way:

     __traits(classInstanceSize, Foo)

Ali


More information about the Digitalmars-d-learn mailing list