Recent

Author Topic: How to declare generic type restriction for enums?  (Read 433 times)

Eugene Loza

  • Hero Member
  • *****
  • Posts: 729
    • My games in Pascal
How to declare generic type restriction for enums?
« on: August 14, 2024, 08:01:12 pm »
I wonder if there is a way to put restriction on generic type to be an enum? I mean, the code below compiles and works exactly as expected, but I wonder if it can be made more me-proof (aka fool-proof) to make sure it's never specialized for something that cannot be asked to for I in T or GetEnumName?

Code: Pascal  [Select][+][-]
  1. generic function EnumToStr<T>(const EnumValue: T): String;
  2. begin
  3.   Exit(GetEnumName(TypeInfo(T), Ord(EnumValue)));
  4. end;
  5. generic function StrToEnum<T>(const EnumString: String): T;
  6. var
  7.   I: T;
  8. begin
  9.   for I in T do
  10.     if specialize EnumToStr<T>(I) = EnumString then
  11.       Exit(I);
  12.   raise EEnumConversionError.CreateFmt('Cannot find %s value: "%s"', [PTypeInfo(TypeInfo(T))^.Name, EnumString]);
  13. end;

I see how to make that for more complex types, but specifically for enums?
My FOSS games in FreePascal&CastleGameEngine: https://decoherence.itch.io/ (Sources: https://gitlab.com/EugeneLoza)

Thaddy

  • Hero Member
  • *****
  • Posts: 15923
  • Censorship about opinions does not belong here.
Re: How to declare generic type restriction for enums?
« Reply #1 on: August 14, 2024, 09:11:59 pm »
This is not yet possible, although there is a feature request for it.
As I understand that is quite well received by the core developers, but, as usual, time and priorities are the issue.
Enums and ordinals in general: the proposal is for ordinals, which includes enums of course. <T:ordinal>
Although enums with assigned values will likely not be supported.

PascalDragon has responded to a similar post, and/or an f.r on the bugtracker, afaik.
« Last Edit: August 14, 2024, 09:27:59 pm by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

 

TinyPortal © 2005-2018