Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: determine actual type of a generic?

Is there any way to determine the type of a variable passed as an argument to a method? Consider the class:

TSomeClass = class
  procedure AddToList<T: TDataType; U: TListClass<T>>(Element: T; List: U);
end;

with the method implementation

procedure TSomeClass.AddToList<T, U>(Element: T; List: U);
begin
  if Element is TInt then
    List.AddElement(TInt.Create(XXX))
  else if Element is TString then
    List.AddElement(TString.Create(YYY));
end;

where TInt.Create() and TString.Create() have different sets of arguments, yet, they both inherit from TDataType.

Now, I know the is-operator can't be used like this, but is there a legal alternative that does what I'm asking here?

like image 942
conciliator Avatar asked Nov 18 '09 13:11

conciliator


People also ask

What is generic data type?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

What is generic type arguments?

The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.


1 Answers

Not being able to use the is operator here is a known issue, but there's a pretty simple workaround.

  if TObject(Element) is TInt then
    List.AddElement(TInt.Create(XXX))

Also, since the type of a generic is part of the class and is known at compile-time, you might be better off restructuring your code. Make two different generic classes, one of which accepts a TInt as its <T> parameter, and the other of which accepts a TString. Put the type-specific functionality into them at that level, and have them descend from a common ancestor for shared functionality.

like image 136
Mason Wheeler Avatar answered Sep 23 '22 02:09

Mason Wheeler