Fields size property

Dejan Lekic dejan.lekic at gmail.com
Fri Nov 18 04:15:00 PST 2011


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() { }

Sure it can be useful sometimes to know (roughly) the size of your classes.
I modified the function to:

auto getFieldsSizeOf(T)() {
  size_t result;
  foreach (type; RepresentationTypeTuple!T) {
    static if (is(type == class) ) {
      result += getFieldsSizeOf!type();
    } else {
      result += type.sizeof;
    }
  }
  return result;
}

As you can see, it goes little bit deeper so code like this:
    class Bar { int x, y; Foo f; }
    writeln(fieldsSizeOf!Bar);
gives us 16 as output not 8.



More information about the Digitalmars-d-learn mailing list