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

Michael Van Canneyt michael at freepascal.org
Tue Jul 16 14:35:43 CEST 2019



On Sat, 13 Jul 2019, Ben Grasset wrote:

> 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
>        ]
>      )
>    );

For the record:

The above will not work in delphi for at least 2 reasons:
1. Simple fuctions are not supported. Can be worked around by making it part
of a record.
2. The Low(T) does not work, as there is no way to tell Delphi that T must
be an enum.

Michael.


More information about the fpc-devel mailing list