Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit class with generic method?

There is a class

TFoo = class
  function GetValue<T>: T;
  procedure SetValue<T>(AValue: T);
end;

The compiler doesn't allow to define methods of this class as virtual. How class

TChildFoo = class(TFoo)

may use methods of ancestor?

like image 917
user2448862 Avatar asked Oct 20 '25 08:10

user2448862


1 Answers

As you have observed, generic methods cannot be virtual. This type

type
  TFoo = class
    function Bar<T>: T; virtual;
  end;

is rejected with the compiler with the following error:

E2533 Virtual, dynamic and message methods cannot have type parameters

Your class is declared like this:

type
  TFoo = class
    function GetValue<T>: T;
    procedure SetValue<T>(AValue: T);
  end;

and you ask how a child class can use these methods. For instance, you can do this:

type
  TChildFoo = class(TFoo)
    procedure DoSomething<T>;
  end;

....

procedure TChildFoo.DoSomething<T>;
begin
  SetValue(GetValue<T>);
end;

In other words, you can certainly use these methods in the parent class. You just cannot declare them to be virtual and override them.

If you have a parameterized class (rather than a parameterized method) then you can declare virtual methods, and override them.

type
  TFoo<T> = class
    function Bar: T; virtual;
  end;

  TChildFoo<T> = class(TFoo<T>)
    function Bar: T; override;
  end;

So, these are your options. As to how to solve your problem, that depends very much on what the problem is.

like image 61
David Heffernan Avatar answered Oct 22 '25 00:10

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!