enum value vs. immutable

Maxim Fomin maxim at maxim-fomin.ru
Sun Dec 1 23:48:44 PST 2013


On Monday, 2 December 2013 at 07:27:25 UTC, Ali Çehreli wrote:
> On 12/01/2013 09:57 PM, CJS wrote:
>
> > I was reading the enum page of Ali Çehreli's (excellent) D
> book
> > (http://ddili.org/ders/d.en/enum.html), and I'm confused by
> an enum
> > value (not enum type), such as
> >     enum secondsPerDay = 60 * 60 * 24;
> > In that situation I would have used an immutable variable. Is
> there any
> > reason to prefer enum vs. immutable when defining constants?
>
> After realizing the other day that even 'static const' can be 
> used for template instantiations, I am not sure myself anymore. 
> :)
>
> Simple rules are great. I wanted to accept the following 
> guidelines, none of which are clear cut:
>
> 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.

>
> 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.

It is C++ism like follwoing code:

struct S { public: this(type){} ... }

or

static Type t; // in module scope




More information about the Digitalmars-d-learn mailing list