[fpc-pascal] Compatibility of very similar generic types

Felipe Monteiro de Carvalho felipemonteiro.carvalho at gmail.com
Thu Aug 18 10:57:15 CEST 2016


Hello,

Consider this:

TSubClass1 = class(TSomeClass)...;
TSubClass2 = class(TSomeClass)...;

TSubClass1Vector = specialize TVector<TSubClass1>;
TSubClass2Vector = specialize TVector<TSubClass2>;
TSomeClassVector = specialize TVector<TSomeClass>;

And I want to write a function like:

procedure WriteVector_To_DM(ADest: TDataManager; ASelf: TSomeClassVector);
procedure ReadVector_From_DM(AFrom: TDataManager; var ASelf: TSomeClassVector);

So according to the compiler warnings this is impossible, and I need
to write 3 functions to cover the 3 specializations, even if those
functions would be identical. Which sucks, because in the real case I
have like 10 nearly identical specializations, then I need 10
identical copy+pasted functions... of course I could use
TSomeClassVector everywhere, but this negates the advantages of using
generics in the first place which was type safety and elegancy.

Of course I am not satisfied to copy+paste 10 times and maintain the
copy+pasted mirrors in every change, so I simply wrote only 1 function
for the base class and I call it like this:

var
  myobj: TSubClass1Vector;
begin
  ....
  ReadVector_From_DM(MyDM, TSomeClassVector(myobj));

Yes, I could write the read/write functions in the vector itself, but
then the vector would need to know about TDataManager, which it is not
supposed to know really :(

The rationale here is that I only use functions from TSubClass1 that
are in TSomeClass, and I can't see how it could go wrong,

I understand that the compiler will generate 3 copies of the same
code: 1 time for TSubClass1Vector, 1 time for TSubClass2Vector and
another for TSomeClassVector. But all those copies should be fully
compatible, considering that:

A> The generic class cannot use anything specific from TSubClass1
since it doesn't know even that we are talking about a class, it could
be an int
B> All classes are equal sized pointers

My conclusion is that doing what I am doing will work, and it can't
possibly fail.

Now I understand that some people will scream: DON'T DO THIS.

But my question is: Is there any real reason why I am wrong and will
fail in some future compiler version or something, or while not
recommended I am correct that there is no real reason why it could
possibly fail. Considering my points above?

thanks,
-- 
Felipe Monteiro de Carvalho



More information about the fpc-pascal mailing list