views:

250

answers:

2

Is there any way to determine the size in bytes of something like

TItem <T> = record
  Data : T;
end;

Can I write something like

function TItem <T>.GetByteSize : Integer;
begin
if (T = String) then
  Result := GetStringByteSize (Data as String)
else
  Result := SizeOf (Data);
end;

or perhaps with the help of specialization?

function TItem <String>.GetByteSize : Integer;
begin
  Result := GetStringByteSize (Data)
end;

function TItem <T>.GetByteSize : Integer;
begin
  Result := SizeOf (Data);
end;

Thanks!

A: 

No, you can't specialize depending on type as far as I know

+2  A: 

Is there something wrong with taking the size of the instantiated type?

SizeOf(TItem<string>)

Or you could define GetByteSize like this:

function TItem <T>.GetByteSize : Integer;
begin
  Result := SizeOf(TItem<T>);
end;
Barry Kelly
I want GetByteSize to return the byte size of the object including the size of the data members, i.e. for T=String, i want something like "SizeOf (Data) + Length (Data) * SizeOf(Char) + 4"
Smasher
That's a very different question, and is not specific to generics. The problems with trying to calculate the kind of recursive size you're talking about are cycles (for object references) and sharing. For T=String, for example, you (a) should be adding 12, not 4 (codePage:2, elemSize:2, refCnt:4, length:4), and (b) what if the string is shared (refCnt > 1)?
Barry Kelly
I know that this is in general a very hard problem (I posted a question concerning this before), but I only want this for this special scenario, where String is the only type that needs extra treatment (for every other type I will just use SizeOf). I decided to see sharing as an optimization and compute a "worst-case size".
Smasher