Created
December 21, 2017 11:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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