Class References

Maxim Fomin maxim at maxim-fomin.ru
Mon Oct 28 09:15:15 PDT 2013


On Monday, 28 October 2013 at 12:10:37 UTC, John Colvin wrote:
> On Monday, 28 October 2013 at 11:22:03 UTC, Jeroen Bollen wrote:
>> Is it possible in D to create an enum of class references?
>> Something around the lines of:
>>
>> enum ClassReferences : Interface {
>>    CLASS1 = &ClassOne,
>>    CLASS2 = &ClassTwo
>> }
>
> Short answer: No
>
> Long answer: the enum values must be compile-time constants, 
> that's what enums are all about. Addresses and references are 
> not compile-time constants.

This is an arbitrary limitation imposed by Don and I disagree 
with him. According to opinion you presented providing classes at 
CT requires having "addresses" but it can be viewed other way - 
providing classes at CT requires some valid value which should be 
preserved for using in RT. For example, nobody complains that 
having enumeration constant or module scope immutable qualified 
basic type int at CT requires to have some "address". Although 
int belongs to value type category, int as module variable has 
"address". Example to illustrate issue:

enum E : int[] { A = [0,1] }

immutable EI = [0,1];

enum EE = [0, 1];

void main()
{
    E e1, e2;
    assert (e1 == e2 && e1 == [0,1]);
    e1[0] = 1;
    assert(e2[0] == 0);
    //EI[0] = 1; // Error: cannot modify immutable expression EI[0]
    assert(EI[0] == 0);
    // EE[0] = 1; // Error: constant [0, 1][0] is not an lvalue
    assert(EE[0] == 0);
}

Dynamic arrays like classes are "reference" types, so there are 
"addresses" involved. Not only this shows that CT references are 
possible, but that dmd can support similar behavior for classes. 
Replace int[] with some class and you will arrive that there is 
something wrong about idea that "enum values must be compile-time 
constants, addresses and references are not compile-time 
constants, thus reference types can't be compile-time 
expressions".


More information about the Digitalmars-d-learn mailing list