Search code examples
delphigenericspascaldelphi-xe6

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;

ie: 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 this is possible in pascal


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;