i have a problem about conversion of type using overload of operator, here i have an full example code:
program OVerloads;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
TMyRange = record
private type
TMyRangeEnum = 1 .. 90;
var
FMyRangeEnum: TMyRangeEnum;
public
class operator Implicit(const Value: Integer): TMyRange;
class operator Implicit(const Value: TMyRange): Integer;
class operator Explicit(const Value: Integer): TMyRange;
class operator Explicit(const Value: TMyRange): Integer;
end;
class operator TMyRange.Implicit(const Value: Integer): TMyRange;
begin
Result.FMyRangeEnum := Value;
end;
class operator TMyRange.Implicit(const Value: TMyRange): Integer;
begin
Result := Value.FMyRangeEnum;
end;
class operator TMyRange.Explicit(const Value: Integer): TMyRange;
begin
Result.FMyRangeEnum := Value;
end;
class operator TMyRange.Explicit(const Value: TMyRange): Integer;
begin
Result := Value.FMyRangeEnum;
end;
var
MyValue: TMyRange;
MyVar: TMyRange; // (or Integer, not change nothing)
MyArr: array[1..90] of TMyRange; // (or Integer, not change nothing)
begin
try
{ TODO -oUser -cConsole Main : Insert code here }
MyValue := 90;
Writeln(MyValue); // [1] Not work, error: E2054 Illegal in Write/Writeln statement
Writeln(Integer(MyValue)); // Work
MyVar := MyArr[MyValue]; // Not work, error: E2010 Incompatible types: 'Integer' and 'TMyRange'
MyVar := MyArr[Integer(MyValue)]; // work
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
Probably i have forgotten something, but as i can solve problem [1] in mnode that not need explicit all time Integer(myValue) ?
Thanks again, very much.
You appear to be overcomplicating this. Define a range type like this:
Then declare your array like this:
And that’s it.
For whatever reason, you assert that you need to use a record here with operator overloading. Be that as it may, but you have pretty much identified that operator overloading implicit casts can not be used to shoehorn your type to be compatible with
Writelnand integer array indexing. I can’t find any documentation that describes these scenarios, but it’s pretty clear that the compiler won’t let you do what you want.So far as I can tell, you can rely on the implicit cast for actual parameters and the right hand side of assignment statements.
Here is my minimal sample to demonstrate the options:
Notes: