Skip to content

Instantly share code, notes, and snippets.

@jpluimers
Created December 21, 2017 11:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpluimers/89b8e6a97908601254f87ee41807ca4f to your computer and use it in GitHub Desktop.
Save jpluimers/89b8e6a97908601254f87ee41807ca4f to your computer and use it in GitHub Desktop.
Some examples of the "E2015: Operator not applicable to this operand type" when using generics
program E2015WithGenerics;
uses
System.SysUtils;
{$APPTYPE CONSOLE}
{$R *.res}
type
TMyAncestor = class
end;
TMyClass = class(TMyAncestor)
strict protected
function GetClassInstance<T: class>: T;
function GetTMyAncestorInstance<T: TMyAncestor>: T;
// function GetTMyClassInstance<T: TMyClass>: T; // [dcc32 Error] E2086 Type 'TMyClass' is not yet completely defined
end;
function TMyClass.GetClassInstance<T>: T;
var
lClassType: TClass;
begin
lClassType := T;
if lClassType = TMyClass then
begin
Result := T(Self)
end
else if T = TMyClass then
begin
Result := T(Self)
end
// else if lClassType is TMyClass then // [dcc32 Error] E2015 Operator not applicable to this operand type
// begin
// Result := T(Self)
// end
// else if T is TMyClass then // [dcc32 Error] E2015 Operator not applicable to this operand type
// begin
// Result := T(Self)
// end
else if lClassType.InheritsFrom(TMyClass) then
begin
Result := T(Self)
end
else if T.InheritsFrom(TMyClass) then
begin
Result := T(Self)
end
else
begin
raise ENotSupportedException.CreateFmt('GetClassInstance fails for class %s', [lClassType.ClassName]);
end;
end;
function TMyClass.GetTMyAncestorInstance<T>: T;
var
lClassType: TClass;
begin
lClassType := T;
if lClassType = TMyClass then
begin
Result := T(Self)
end
// else if T = TMyClass then // [dcc32 Error] E2015 Operator not applicable to this operand type
// begin
// Result := T(Self)
// end
// else if lClassType is TMyClass then // [dcc32 Error] E2015 Operator not applicable to this operand type
// begin
// Result := T(Self)
// end
// else if T is TMyClass then // [dcc32 Error] E2015 Operator not applicable to this operand type
// begin
// Result := T(Self)
// end
else if lClassType.InheritsFrom(TMyClass) then
begin
Result := T(Self)
end
else if T.InheritsFrom(TMyClass) then
begin
Result := T(Self)
end
else
begin
raise ENotSupportedException.CreateFmt('GetTMyAncestorInstance fails for class %s', [lClassType.ClassName]);
end;
end;
//function TMyClass.GetTMyClassInstance<T>: T;
//begin
////...
//end;
begin
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment