Mutable enums

Timon Gehr timon.gehr at gmx.ch
Mon Nov 14 00:30:29 PST 2011


On 11/14/2011 09:27 AM, Timon Gehr wrote:
> On 11/14/2011 01:02 AM, bearophile wrote:
>> Jonathan M Davis:
>>
>>>> import std.algorithm;
>>>> void main() {
>>>> enum a = [3, 1, 2];
>>>> enum s = sort(a);
>>>> assert(equal(a, [3, 1, 2]));
>>>> assert(equal(s, [1, 2, 3]));
>>>> }
>>>
>>> It's not a bug. Those an manifest constants. They're copy-pasted into
>>> whatever
>>> code you used them in. So,
>>>
>>> enum a = [3, 1, 2];
>>> enum s = sort(a);
>>>
>>> is equivalent to
>>>
>>> enum a = [3, 1, 2];
>>> enum s = sort([3, 1, 2]);
>>
>> You are right, there's no DMD bug here. Yet, it's a bit surprising to
>> sort in-place a "constant". I have to stop thinking of them as
>> constants. I don't like this design of enums...
>
> It is the right design. Why should enum imply const or immutable? (or
> inout, for that matter). They are completely orthogonal.
>
> enum Enum{
> opt1,
> opt2,
> }
>
> void main(){
> auto moo = Enum.opt1;
> moo = Enum.opt2; // who would seriously want an error here???
> }
>
>
> enum a = [1,2,3];
>
> void main(){
> auto x = a;
> x = [2,1,3]; // ditto
> }
>
>
>>
>> On the other hand this gives the error message I was looking for,
>> until today I didn't even think about const enums:
>>
>> import std.algorithm;
>> const enum a = [1, 2];
>> void main() {
>> sort(a);
>> }
>>
>>
>> So I guess I'll start using "cont enum" and "immutable enum" instead
>> of enums :-)
>>
>
> You can do that, but they are not a full replacement. How would you get
> a sorted version of such an enum, for instance? =)

(.dup, obviously.)


More information about the Digitalmars-d-learn mailing list