delphigenericsdelphi-xe6typeinfo

Testing the type of a generic in Delphi


I want some way to write a function in Delphi like the following

procedure Foo<T>;
begin
    if T = String then
    begin
        //Do something
    end;

    if T = Double then
    begin
        //Do something else
    end;
end;

That means I want to be able to do different things based on a generic type.

I’ve tried using TypeInfo in System but this seems to be suited to objects rather than generic types.

I’m not even sure if this is possible in Delphi.


Solution

  • TypeInfo should work:

    type
      TTest = class
        class procedure Foo<T>;
      end;
    
    class procedure TTest.Foo<T>;
    begin
      if TypeInfo(T) = TypeInfo(string) then
        Writeln('string')
      else if TypeInfo(T) = TypeInfo(Double) then
        Writeln('Double')
      else
        Writeln(PTypeInfo(TypeInfo(T))^.Name);
    end;
    
    procedure Main;
    begin
      TTest.Foo<string>;
      TTest.Foo<Double>;
      TTest.Foo<Single>;
    end;