[fpc-devel] Allow object type property getter to expose a field as one of its base/parent types (patch included)
Kostas Michalopoulos
badsectoracula at gmail.com
Thu Jun 4 03:45:30 CEST 2020
Hello,
I'd like to add a small feature for property getters to allow
themselves be exposed as a base type of the real field. Example:
===
program ExposeDerivedAsBase;
{$mode objfpc}
type
TBase = class
end;
TDerived = class(TBase)
end;
TSomething = class
private
FProp: TDerived;
public
property Prop: TBase read FProp;
end;
begin
end.
===
The reasoning for this patch is to expose fields directly, without any
additional overheads while being able to hide the real type that the
object uses internally.
One use on a project that i'm currently working on is collections that
are implemented as two classes, one base class that provides a
read-only view of the items in the collection and a derived class that
provides read-write access (this is similar to how C# has List<T>
implement IReadOnlyList<T> but using a class instead). This approach
is actually implemented in two collections, one that uses
object types so that the collection data can be embedded inside other
types (as opposed to creating separate objects on the heap) and one
that uses class types that wraps around the object type (this is
mainly to be able to expose the collection to RTTI for a custom
serialization system i'm working on that relies on properties and
custom attributes for its functionality).
You can find a Mantis entry with the patch here:
https://bugs.freepascal.org/view.php?id=37175
This basically adds an additional check in
add_getter_or_setter_for_sym when the call to compare_defs doesn't
return an adequate value to see if the relevant defs are compatible
objects, which should not introduce any additional overhead in
existing code (initially i considered modifying compare_defs_ext but i
noticed that it is used in several places so i found this special case
safer).
Kostas Michalopoulos
More information about the fpc-devel
mailing list