Is there a way to make a class variable visible but constant to outsiders, but changeable (mutable) to the class itself?

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 24 11:28:44 PDT 2016


On Tuesday, 24 May 2016 at 15:07:55 UTC, Jonathan M Davis wrote:
> On Tuesday, May 24, 2016 10:10:16 Steven Schveighoffer via 
> Digitalmars-d-learn wrote:
>> A while ago, I discovered that this works.
>>
>> class C {
>>     union
>>     {
>>        private int _my_var;
>>        public const int my_var;
>>     }
>>     void do_something() { _my_var = 4; }
>> }
>
> Yeah. That's basically what Rebindable does, though in its 
> case, it's not really allowing you to mutate any data, just 
> what the reference refers to. Regardless, it does seem like a 
> hole in the type system.
>
> - Jonathan M Davis

I don't believe so. H. S. Teoh recently fixed a definite bug when 
you have something like:

struct S
{
     union
     {
         int n1;
         immutable int n2;
     }
}

But I'm pretty sure the case where n2 is const was purposely not 
fixed as it doesn't break the type system. The value of a const 
variable can be changed at any time out from under you, so a 
union of a mutable and const int does not break any type system 
guarantees.


More information about the Digitalmars-d-learn mailing list