[fpc-devel] [Suggestion] Enumeration range-check intrinsic

Ben Grasset operator97 at gmail.com
Sat Jul 13 21:45:25 CEST 2019


On Sat, Jul 13, 2019 at 2:37 PM Ondrej Pokorny <lazarus at kluug.net> wrote:

> I do exactly the same - check the low/high bounds in a type helper :)
> Yes, and I am tired of typing it as well :)
>

You can pretty easily write a generic function that will work on pretty
much any enum for this, BTW:

program Example;

{$mode Delphi}

uses TypInfo, SysUtils;

function TryConvert<T>(const Value: SizeInt): T; inline;
begin
  if (Value >= SizeInt(Low(T))) and (Value <= SizeInt(High(T))) then
    Result := T(Value)
  else
    raise EConvertError.Create(
      Format(
        'Invalid value for %s : %d', [
          PTypeInfo(TypeInfo(T))^.Name,
          Value
        ]
      )
    );
end;

type
  Letter = (A, B, C);

begin
  WriteLn(TryConvert<Letter>(0));
  WriteLn(TryConvert<Letter>(1));
  WriteLn(TryConvert<Letter>(2));
  // Exception!
  WriteLn(TryConvert<Letter>(3));
end.

The exception printing "EConvertError: Invalid value for Letter : 3", of
course.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20190713/97337f9d/attachment.html>


More information about the fpc-devel mailing list