Last active
March 13, 2021 16:58
-
-
Save jpluimers/c1c5e68dc94891e10d454814c824e38c to your computer and use it in GitHub Desktop.
In Delphi, you cannot do math with generic types, as you will get "E2015 Operator not applicable to this operand type" because there is no way to constraint the generic type to be floating point or ordinal.
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
unit AxisUnit; | |
interface | |
type | |
TAxis<T: record> = record | |
fMin, fMax, fRange: T; | |
fStart, fEnd, fExtent: single; | |
function CalcCasted( const AScalar: T ): single; | |
function CalcPlain( const AScalar: T ): single; | |
end; | |
implementation | |
function TAxis<T>.CalcCasted(const AScalar: T): single; | |
var | |
Offset: single; | |
NormalisedOffset: single; | |
ScaledOffset: single; | |
begin | |
// First 2 lines give the same error: E2089 Invalid typecast | |
Offset := single(AScalar) - fMin; | |
NormalisedOffset := Offset / single(fRange); | |
ScaledOffset := NormalisedOffset * fExtent; | |
Result := fStart + ScaledOffset; | |
end; | |
function TAxis<T>.CalcPlain(const AScalar: T): single; | |
var | |
Offset: T; | |
NormalisedOffset: T; | |
ScaledOffset: T; | |
begin | |
// All 4 lines give the same error: E2015 Operator not applicable to this operand type | |
Offset := AScalar - fMin; | |
NormalisedOffset := Offset / fRange; | |
ScaledOffset := NormalisedOffset * fExtent; | |
Result := fStart + ScaledOffset; | |
end; | |
end. |
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 DelphiMathAndGenerics; | |
uses | |
AxisUnit in 'AxisUnit.pas'; | |
var | |
rXAxis: TAxis<TDateTime>; | |
rYAxis: TAxis<single>; | |
begin | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment