skip generic parameter on demand

2019-07-17 03:13发布

I found this definition of an generic class in the web :

  TVertex<T> = class
  public
    Name: String;
    OutputAttributes: TVertexOutputAttributes;
    Marker: Boolean;
    Data: T; // User-defined data attribute
    function HasAdditionalAttributes: Boolean;
    constructor Create();
    procedure Mark;
    procedure UnMark;
  end;

a single instance of a TVertex class is created with the following line of code :

  A := TVertex<Integer>.Create();
  A.Name := 'A';

in this example we define T as Integer data Type. My question goes now like this :

If my use case does not need any assigend datatype T it would be much better / logical if I can skip the specification on the datatype. I failed with :

   A := TVertex<>.Create();
  A.Name := 'A';

Any change to avoid the handover of the datatype at the create process ???

1条回答
何必那么认真
2楼-- · 2019-07-17 03:19

What you are explicitly asking for has one obvious flaw. What will the compiler do with this declaration?

Data: T; // User-defined data attribute

If you don't supply a T, then the compiler doesn't know what to do.

This observation leads us to one possible approach. If you don't want to supply T then presumably you don't want the class to contain this member. How can it contain that member if its type is not supplied? So define a non-generic version:

type
  TVertex = class
  public
    Name: String;
    OutputAttributes: TVertexOutputAttributes;
    Marker: Boolean;
  end;

And then derive your generic version from this:

type
  TVertex<T> = class(TVertex)
  public
    Data: T; // User-defined data attribute
  end;

Clearly you would need to determine in which class the methods should be declared and implemented. Clearly any methods that did not rely on Data could be implemented in the non-generic class.

查看更多
登录 后发表回答