www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - properties using template mixins and alias this

I came upon realization that you can already create properties 
accepting various operators in D, using a template mixin. The only 
missing part is getting the value without a getter function.

struct Z
{
	int value2Cache;
	
	template Property()
	{
		int value;
		
		void opAssign(int newValue) { value = newValue; value2Cache = value * 
value; }
		void opAddAssign(int otherValue) { value += otherValue; value2Cache = 
value * value; }
		int get() { return value; }
	}
	
	mixin Property property;
}

int main(char[][] m)
{
	Z z;
	z.property = 1;
	z.property += 1;
	assert(z.property.get == 2);
	assert(z.value2Cache == 4);
	
	return 0;
}


Perhaps "alias value this;" could do the trick, but alas it only works 
with structs and classes currently, not templates, as this case 
demonstrate:

struct Z
{
        int value2Cache;

        template Property()
        {
                int value;
                alias value this;

                void opAssign(int newValue) { value = newValue;
value2Cache = value * value; }
                void opAddAssign(int otherValue) { value += otherValue;
value2Cache = value * value; }
        }

        mixin Property property;
}

int main(char[][] m)
{
        Z z;
        z.property = 1;
        z.property += 1;
        assert(z.property == 2);
        assert(z.value2Cache == 4);

        return 0;
}

property.d(24): Error: expression has no value
property.d(8): Error: alias this alias this can only appear in struct 
or class declaration, not main
property.d(16): Error: mixin property.main.Property!() error instantiating


-- 
Michel Fortin
michel.fortin michelf.com
http://michelf.com/
Apr 13 2009