Jump to content
Sign in to follow this  
Dave Novo

casting an object as a interface via generic

Recommended Posts

Hello,

I am using Delphi Seattle. I am wondering if something like this is possible. I cannot figure out how query if the object supports T at the base level.


 

TMyClass=class
public
  function MyFunc<T:Interface>:T;
end


TMyDescendent=class(TMyClass,ISomeInterface)
public
   function ReturnMyInt:ISomeInterface;
end;


function TMyDescendent.ReturnMyInt:ISomeInterface
begin
  result:=MyFunc<ISomeInterface>;
end


function TMyClass.MyFunc<T>:T
begin
   // do some stuff here
  Supports(self,T,result);// does not compile
  result:=self as T;// does not compile
end;

 

of course, I can always chane MyFunc to math the Supports signature (i.e. pass in IID and out Obj) but I was wondering if there was a way to do this with generics

Edited by Dave Novo

Share this post


Link to post
uses
  TypInfo;

function TMyClass.MyFunc<T>: T;
var
  p: PTypeData;
begin
  p := GetTypeData(TypeInfo(T));
  Assert(ifHasGuid in p.IntfFlags);
  Supports(Self, p.GUID, Result);
end;

 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×