[fpc-devel] Generic helpers
Hairy Pixels
genericptr at gmail.com
Mon Jan 9 14:35:14 CET 2023
Hey guys, I was thinking about how nice generic type helpers would be today and remembered I did a mostly functional branch over 6 months ago so I fixed it up and posted it on gitlab. There’s a nasty merge error with main I need to fix but you can test it anyways.
For the helper type I supported: single types, dynamic arrays, static arrays, sets and classes and records.
Is this acceptable how I did it? I never know. :)
The main strange thing is supported compound types in helper types (like “array of T” or "generic TMyHelper<T> = class helper for specialize TMyClass<T>” for specialized generic classes/records) but I argue these are necessary for the feature to be complete.
https://gitlab.com/genericptr/free-pascal/-/commits/generic_helpers
For example with simple types:
=====================
program tgenhelper1;
type
generic TMyHelper<T> = type helper for T
procedure Print;
end;
TIntHelper = specialize TMyHelper<Integer>;
procedure TMyHelper.Print;
begin
writeln(self);
end;
var
i: integer = 100;
begin
i.Print;
end.
=====================
Or dynamic arrays:
=====================
program tgenhelper2;
type
generic TArrayHelper<T> = type helper for array of T
function Count: integer;
end;
TIntegerArrayHelper = specialize TArrayHelper<Integer>;
function TArrayHelper.Count: integer;
begin
result := Length(self);
end;
var
a: array of integer;
begin
a := [1,2,3];
writeln(a.Count); // array of T is compatible with TIntegerArrayHelper
end.
=====================
Or classes:
=====================
program tgenhelper4;
type
generic TMyHelper<T: class> = class helper for T
procedure Print;
end;
TObjectHelper = specialize TMyHelper<TObject>;
procedure TMyHelper.Print;
begin
writeln(ClassName);
end;
var
c: TObject;
begin
c := TObject.Create;
c.Print;
end.
=====================
Regards,
Ryan Joseph
More information about the fpc-devel
mailing list