Constant relationships between non-constant objects

H. S. Teoh via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 17 22:50:26 PDT 2014


On Wed, Jun 18, 2014 at 02:26:24AM +0000, Sebastian Unger via Digitalmars-d wrote:
[...]
> But why NOT include head-const if there are also good use cases for
> it?

Because it can be easily emulated? Here's a working, first stab at it:

----- headconst.d -----
	module headconst;

	struct HeadConst(T) {
		private T impl;
		@property T get() { return impl; }
		alias get this; // magic ;-)
		this(T t) { impl = t; }

		// This is what stops rebinding
		void opAssign(T)(T) {
			static assert(false, "Cannot assign to HeadConst");
		}
	}
------------------

----- test.d -----
import headconst;

unittest {
	class MyOtherClass {
		int x = 123;
	}
	class MyClass {
		HeadConst!MyOtherClass other;
		this() {
			other = HeadConst!MyOtherClass(new MyOtherClass);
		}
	}
	auto obj = new MyClass;

	// You can freely access the MyOtherClass instance in MyClass:
	assert(obj.other.x == 123);

	// And freely modify it:
	obj.other.x++;
	assert(obj.other.x == 124);

	// But you can't rebind it:
	//obj.other = new MyOtherClass; // error: cannot assign to HeadConst
}
void main() {}
------------------


Of course, there are some holes in the current implementation that need
to be patched up, but this should get you started.

Hope this helps. :)


T

-- 
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan


More information about the Digitalmars-d mailing list