开发者

Delphi: generic and type constraints

Is it possible to constrain the 开发者_如何学Ctype of generic to, say, two different classes?

Like so:

TSomeClass<T: FirstClass; T: SecondClass> = class
  // ...
end;

(Sorry about the lack of formatting - the SO tool bar has disappeared from my browser). I know the above won't compile, its only written so to give you guys an idea. I tried

TSomeClass<T: FirstClass, SecondClass> = class
  // ...
end;

but then I wasn't allowed to write

procedure TSomeClass.SomeMethod<T> (Param1: string);

Is this even possible?


No, it's not possible. How should the compiler be able to statically verify that your method calls are valid?

Note, that

TSomeClass <T : FirstClass, SecondClass>

is not a valid type constraint. You cannot combine multiple class constraints. You can combine a class constraint with some interface constraints though. But even then

TSomeClass <T : TSomeClass, ISomeInterface>

means, that the generic type has to descend from TSomeClass and implement ISomeInterface.

So the only thing you can do is to extract the stuff that is common between FirstClass and SecondClass, put it in an interface and use an interface constraint:

TSomeClass <T : IOnePointFive>

Perhaps you can give some more details about what you want to achieve.


Having both classes implement the same interface is the way to go. Then constrain the generic to that interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜