BenLaz
BenLaz

Reputation: 1005

Delphi error with generics and interfaces

The following Delphi code does not compile with an error in Foo function, but the Foo2 function compile. It drive me crazy, does anyone have an idea ?

type

  IA<T> = Interface
  end;

  TA<T> = class(TInterfacedObject, IA<T>)
    function Foo<V> : IA<V>;
  end;

  TB<U,T> = class(TA<T>)
  end;

  TC = class
    function Foo2<T,V> : IA<V>;
  end;


implementation

{ TA<T> }

function TA<T>.Foo<V>: IA<V>;
begin
  Result := TB<T,V>.Create;
end;

{ TC }

function TC.Foo2<T,V>: IA<V>;
begin
  Result := TB<T,V>.Create;
end;

Upvotes: 1

Views: 102

Answers (1)

David Heffernan
David Heffernan

Reputation: 613562

This does look odd, and I suspect that it is a bug. You can work around it by declaring that TB<U, T> implements IA<T>. Change

TB<U, T> = class(TA<T>)

to

TB<U, T> = class(TA<T>, IA<T>)

Note that your code with all the generics removed does compile:

type
  IA = interface
  end;

  TA = class(TInterfacedObject, IA)
    function Foo: IA;
  end;

  TB = class(TA)
  end;

  TC = class
    function Foo2: IA;
  end;

function TA.Foo: IA;
begin
  Result := TB.Create;
end;

function TC.Foo2: IA;
begin
  Result := TB.Create;
end;

This would appear to back up my belief that your code is correct and should be accepted by the compiler.

Upvotes: 2

Related Questions