views:

238

answers:

1

I am trying to do the following in Delphi 2010:

TDataConverter = class abstract
public
    function Convert<T>(const AData: T): string; virtual; abstract;
end;

However, I keep getting the following compiler error:

E2533 Virtual, dynamic and message methods cannot have type parameters

I don't quite understand the reason why I can't do this. I can do this in C# e.g.

public abstract class DataConverter
{
    public abstract string Convert<T>(T data);
}

Anyone know the reasoning behind this?

+6  A: 

You can do it in .NET because Delphi and .NET handle generics differently. I don't know enough to go into detail. I do know why you can't do it in Delphi, though.

Every virtual method has to have a slot in the virtual method table for the class. This has to be set up when the unit is compiled so its information can be put into the DCU. (And likewise, every dynamic method has to have an entry in the dynamic method table, at the time when the unit is compiled.)

But if you create generic methods, each time you invoke it in code, a different copy of the code gets created, specific to that type parameter. This is necessary for handling different types in different ways. (If you pass in an interface or a string, for example, it has to take care of the reference count.) But you can't create new virtual methods and new VMT slots for them, since the DCU has already been created and can't be changed now.

Mason Wheeler
.NET instantiates generic types and methods at runtime, and can do the necessary tricks to dispatch virtual generic methods, which will include instantiating all the overrides between the concrete descendant and the original base class definition, as well as using dynamic structures for method dispatching.
Barry Kelly
James