0

I have an Interface

IMyInterface<T>

and a class

TMyClass<T>

and now I want that I can only pass classes to TMyClass as a type, that also implement IMyInterface.

First I tried

TMyClass<T:IMyInterface<T>>

but as expected, now the compiler wants me to give him a type which implements an interface with the type of class itself that implements the interface

Second try was

TMyClass<D,T:IMyInterface<D>> 

where I thought, D would then be the shared DataType, both TMyInterface and TMyClass would use.

So after declaring the class implementing the interface

TMyIntegerClass = class(TInterfacedObject,IMyInterface<Integer>)

The declaration

GMyClass:TMyClass<Integer,TMyIntegerClass>

failed with compiler error:

E2514 Type parameter 'D' must support interface 'IMyInterface<System.Integer>' 

Any pointers?

4
  • 1
    What about using a semicolon instead of a comma: TMyClass<D; T: IMyInterface<D>>, analogue to parameters of a function? Commented Feb 17, 2018 at 16:13
  • That makes no difference. Syntax at this point still okay, but same compiler error in the declaration of the variable. Commented Feb 17, 2018 at 16:16
  • 1
    oh yes, it most definitely makes a difference. See my answer. Commented Feb 17, 2018 at 16:24
  • stackoverflow.com/questions/19682057/… Commented Feb 17, 2018 at 16:42

1 Answer 1

4

This compiles in Delphi 10.2.2 Tokyo:

type
  IMyInterface<T> = interface
  ['{F810B6BC-78F7-4026-BA83-70435150B758}']
  end;

  TMyClass<D; T: IMyInterface<D>> = class // note the semicolon!
  end;

  TMyIntegerClass = class(TInterfacedObject, IMyInterface<Integer>)
  end;

var
  GMyClass: TMyClass<Integer, TMyIntegerClass>;

If, in the declaration of the class, I use <D, T: TSomeType> (comma!) then both D and T are declared to be of the same type, like parameters of a function:

procedure Blah(D, T: TSomeType);

Parameters D and T are of the same type, i.e. TSomeType.

Now, if you pass an Integer for D, you get an error, similar to the one you got. The compiler expects two TSomeType parameters.

But if I use <D; T: TSomeType> then D and T are separate types, i.e. D is of an unknown type and T is of type TSomeType. So now, D is not declared as TSomeType and there is no error if you pass Integer.

Oh, and this is documented too.

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, sorry it actually works, tried it on wrong class... set to accepted answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.