enum value vs. immutable

Ali Çehreli acehreli at yahoo.com
Tue Dec 3 00:28:22 PST 2013


On 12/01/2013 11:48 PM, Maxim Fomin wrote:

 >> 1) Prefer enum first because enum values can be used for template
 >> instantiations.
 >
 > You can instatiate templates not only with enums. Main pro for enums is
 > that they are CT values.

The confusion is, some const values are CT values as well.

 >> 3) Prefer const last as it erases immutable attribute if present. (We
 >> can't know just by looking at a reference to const whether the
 >> original value has been immutable or mutable.)
 >
 > It is interesting to know where such advices come from. Const in D is
 > useless except as as parameter qualifier, method qualifier, tool to
 > alias const data and non-const data and as qualifier of some field -
 > member of aggregate.
 >
 > Writing code like
 >
 > const int i = SOME_VALUE;
 >
 > is loosing advantages of immutable or enum while gaining nothing in 
return.

That works for some types as both enum and immutable have their problems:

* enum is no good for arrays and AAs as it is very likely to be 
unnecessarily slow.

* immutable is no good for types that contain mutable references at 
least during assignment:

struct S
{
     int i;
     int[] others;
}

void main()
{
     auto a = S(42);
     immutable b = a;
// Error: cannot implicitly convert expression (a) of type S to immutable(S)
}

 > It is C++ism like follwoing code:
 >
 > struct S { public: this(type){} ... }
 >
 > or
 >
 > static Type t; // in module scope

Both of those do happen. ;)

Ali



More information about the Digitalmars-d-learn mailing list