Logical Const using a Mutable template

Jesse Phillips jessekphillips+D at gmail.com
Mon Nov 29 23:30:09 PST 2010


This came up in discussion and I think the behavior is safe and usable when wanting to change class data in a const function.

http://article.gmane.org/gmane.comp.lang.d.general/43476

One limitation is that value types declared as Mutable (Mutable!(int)) can not be changed if the encapsulating class is declared immutable. For this reason a Mutable value can not be changed inside a const function. I think this is acceptable.

Another limitation appears to be an issue with alias this. It is commented as a //FIXME in the code.

https://gist.github.com/721066

An example usage looks like:

    class Inner { int n; }

    class A {
        Mutable!(int*) n;
        Mutable!(int)  n2;
        Mutable!(Inner) innerClass;
        this() { n = new int; innerClass = new Inner; }

        void foo( int num ) {
            n2 = num;
        }
        
        void bar( int num ) const {
            innerClass.n = num;
        }
    }

    auto aImmu = new immutable(A);
    auto aMu   = new A;
    int i = 8;
    
    *aImmu.n = i,
    aImmu.bar(6),
    *aMu.n = i,
    aMu.n = &i,
    aMu.n2 = i,
    aMu.bar(6),
    aMu.foo(6),



More information about the Digitalmars-d mailing list