views:

212

answers:

1
type 
  TParent=class
    public
      member1:Integer;
  end;

  TChild=class(TParent)
  public
    member2:Integer;
  end;


  TGArray<T: TParent>=class
    public
      function test:T;
    end;

  implementation

  var g:TGArray<TChild>;

    function TGArray<T>.test:T;
    begin
      Result:=??.create; // <<<<  Problem !
    end;


  begin
    g := TGArray<TChild>.Create;
    g.test.member2 := 1234;
  end.

g.test has to return an instance of the class. I tried multiple things:

1.  Result := Result.create; //Exception
2.  Result := TChildClass.Create; //Error
3.  type TGArray<T: class> = class; //and above 2. The same errors/exceptions.

The purpose of this is to create a generic array of classes. The array is stored inside the generic class and returns instances, but how?

If I accomplish this thing, I will shorten my code 3 times, but I cannot do it. Please suggest any solution.

+7  A: 

You don't say what the error in #2 is, but I'll bet it tells you it requires a constructor constraint. Add one and it should work.

Mason Wheeler
It says "You can accept an answer in 47 seconds" ,Thank you!
John