I am having problems with generics. I do not know how to pass OnCallbackWrapper
to the CallbackWrapper
procedure. I am getting 'incompatible types' error on the following example:
unit uTest;
interface
uses
Generics.Defaults;
type
TGenericCallback<T> = procedure(Fields: T);
type
TSpecificFields = record
A: Integer;
B: Integer;
C: Integer;
end;
const
SpecificFields: TSpecificFields =
(A: 5; B: 4; C: 3);
procedure CallbackWrapper(GenericCallback: TGenericCallback<TSpecificFields>);
implementation
procedure CallbackWrapper(GenericCallback: TGenericCallback<TSpecificFields>);
begin
GenericCallback(SpecificFields);
end;
procedure OnCallbackWrapper(const Fields: TSpecificFields);
begin
Assert(Fields.A = 5);
Assert(Fields.B = 4);
Assert(Fields.C = 3);
end;
procedure Dummy;
begin
CallbackWrapper(OnCallbackWrapper); //Incompatible types here
end;
end.
What am I doing wrong? Thanks.
The type that you declared receives its parameter by value.
TGenericCallback<T> = procedure(Fields: T); // no const
The function you pass is marked with const
.
procedure OnCallbackWrapper(const Fields: TSpecificFields); // const parameter
So the compiler rejects the parameter you attempt to pass as not matching. You need to make both sides match. For example:
TGenericCallback<T> = procedure(const Fields: T);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With