Testing the type of a generic in delphi

懵懂的女人 提交于 2019-12-22 04:06:25

问题


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


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/31042997/testing-the-type-of-a-generic-in-delphi

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