Testing the type of a generic in delphi

本秂侑毒 提交于 2019-12-05 02:09:21

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;
David Heffernan

From XE7 onwards you can use GetTypeKind to find the type kind:

case GetTypeKind(T) of
tkUString:
  ....
tkFloat:
  ....
....
end;

Of course tkFloat identifies all floating point types so you might also test SizeOf(T) = SizeOf(double).

Older versions of Delphi do not have the GetTypeKind intrinsic and you have to use PTypeInfo(TypeInfo(T)).Kind instead. The advantage of GetTypeKind is that the compiler is able to evaluate it and optimise away branches that can be proven not to be selected.

All of this rather defeats the purpose of generics though and one wonders if your problem has a better solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!