Call a method on a generic type?

Why is an error generated in Delphi (XE)?

unit UTest; interface type TTest = class public procedure Foo<T>(A: T); end; implementation { TTest } procedure TTest.Foo<T>(A: T); begin A.Add('hej'); end; end. 

I thought that generic types in Delphi are simply inserted into a generic function, so it will only be an error if it is used with a type that does not have an Add (string) method.

+6
source share
1 answer

A compilation error occurs in your code because the compiler does not know that T has a method named Add that receives one string parameter.

I thought that generic types in Delphi are simply inserted into a generic function, so it will only be an error if it is used with a type that does not have an Add (string) method.

If you use Smalltalk or C ++ templates, your guess would be accurate. However, generics do not match the patterns. For generics, you need to apply a restriction to the type parameter. The restriction should tell the compiler which properties of T should have.

For example, you can restrict T to be obtained from a class that has a suitable Add method. Or you can restrict T to implement the interface using the appropriate Add method.

Documentation link for general Delphi restrictions: http://docwiki.embarcadero.com/RADStudio/en/Constraints_in_Generics

The general restrictions that can be applied are quite limited, which is a bit of a shame. For example, I would like to keep the type in order to have certain mathematical operators. For example, I would like to be able to restrict the type, for example, the + and - operators. However, there are pros and cons for both generics and templates, and therefore I agree that these restrictions are the result of a sound design decision by the Delphi developers.

+8
source

Source: https://habr.com/ru/post/952513/


All Articles