On Friday, 26 September 2014 at 18:18:45 UTC, Steven Schveighoffer wrote:
On 9/26/14 1:36 PM, "Marc =?UTF-8?B?U2Now7x0eiI=?= <schue...@gmx.net>" wrote:

Alternatively, you could create a union with a private and a public member with the same types, but I wouldn't recommend it. Besides, the
members would need to have different names:

    class Foo {
        union {
            private int a;
            public int b;
        }
    }

Hm.. that doesn't provide readonly access to either a or b.

But it gave me an idea:

class Foo {
   union {
      private int _a;
      public const int a;
   }
   void setA(int x) { _a = x; }
}

Hot damn! It works too :) Can't access _a from outside the module, can access a, but can't write it (even from within Foo). It's like an auto-inlined property function.

I don't know how it would affect the optimizer, or the GC scanner. Unions are ugly things...

-Steve

This is really a loot cool and works. Thanks. If private in D had same behavior like in C#/C++, ie, private to scope of where class was declared and not public to the entire module, I guess we could even do:

class Foo {
        union {
                private int a_;

                public @property int a() {
                        return a_;
                }

                private @property void a(int value) {
                        a_ = value;
                }
        }

        //no one need knows the 'a_' (ugly?) identifier
        void setValue(int x)
        {
                a = x;
        }
}

And then

Foo f = new Foo();
f.a = 10; // give a compile error becaus it is private and acessible within Foo class only

BTW: I'm not sure about memory usage where using properties. But it is still cool.

Reply via email to