delphi - Invoke method on generic type? -


why following generate error 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 generic types in delphi inserted generic function, error out if used type don't have add(string) method.

your code produces compilation error because compiler has no way of knowing t has method named add receives single string parameter.

i thought generic types in delphi inserted generic function, error out if used type don't have add(string) method.

if using smalltalk or c++ templates, assumption accurate. however, generics not same templates. generics need apply constraint type parameter. constraint needs tell compiler properties t must have.

for example, constrain t derived class has suitable add method. or constrain t implement interface suitable add method.

documentation link delphi generic constraints: http://docwiki.embarcadero.com/radstudio/en/constraints_in_generics

the generic constraints can applied rather limited, of shame. example, i'd love able constrain type have mathematical operators. example, i'd able constrain type have + , - operators, say. however, there pros , cons both generics , templates, , accept these limitations result of justifiable design decision delphi language designers.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -