Reputation: 6979
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.
Upvotes: 4
Views: 798
Reputation: 27377
procedure OnCallbackWrapper( Fields: TSpecificFields);
begin
Assert(Fields.A = 5);
Assert(Fields.B = 4);
Assert(Fields.C = 3);
end;
or change declaration to
TGenericCallback<T> = procedure(const Fields: T);
A procedure passing parameters by value is not assignment compatible with a procedure which passes parameters by reference. Reference
Upvotes: 7
Reputation: 612964
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);
Upvotes: 8