Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a set type of an enum type within a generic class

I came across some strange behaviour in Delphi XE4.

I can't declare a set type within a generic class, where the ordinal type is declared within the same class.

For example:

TTest<T> = class(TObject)
type
  TEnumType  = (eOne, eTwo, eThree);
  TEnumTypes = set of TEnumType;
end;

The above does not compile. The compiler emits error "E2001: Ordinal type required".

A non-generic class like

TTest = class(TObject)
type
  TEnumType  = (eOne, eTwo, eThree);
  TEnumTypes = set of TEnumType;
end;

does compile.

For the generic class to compile successfully, the ordinal type has to be declared outside the class:

TEnumType  = (eOne, eTwo, eThree);
TTest<T> = class(TObject)
type
  TEnumTypes = set of TEnumType;
end;

  1. Is this behaviour considered a bug? If yes, has it been fixed in a later version?
  2. Does anyone have another workaround? I wanted to declare the types within the class because they are used exclusively in private parts of this class.
like image 486
René Hoffmann Avatar asked Oct 26 '16 08:10

René Hoffmann


People also ask

Can you define an enum within a class?

Yes, we can define an enumeration inside a class. You can retrieve the values in an enumeration using the values() method.

Can generic type be enum?

On a technical level, there's nothing wrong with using an enum as the type used in a generic type.

How do you declare an enum?

An enum is defined using the enum keyword, directly inside a namespace, class, or structure. All the constant names can be declared inside the curly brackets and separated by a comma. The following defines an enum for the weekdays. Above, the WeekDays enum declares members in each line separated by a comma.

Can enum be generic Java?

The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation. This extension need not be stated explicitly in code.


1 Answers

This is indeed a bug that is fixed in later versions. Your code compiles in XE7 for instance. Quite possibly it will compile in XE5 or XE6, but I don't have them immediately to hand to check.

like image 136
David Heffernan Avatar answered Sep 28 '22 02:09

David Heffernan