www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - python's "with" in D

Here's a generic implementation of something similar to python's with statement
as a generic mixin 
for classes. Idea thanks to pa-ching in #d. Have fun!

import std.stdio;

template WithMixin(T, INITS...) {
	static void With(INITS inits, void delegate(T) dg) {
		auto foo=new T(inits);
		scope(exit) delete foo;
		dg(foo);
	}
}

class foo {
	this(char[] c) { writefln("Constructed with ", c); }
	~this() { writefln("Foo destructed"); }
	mixin WithMixin!(foo, char[]);
}

void main() {
	foo.With("test", (foo f) { writefln("Got Foo ", cast(void*)f); });
	writefln("Done");
}

  --downs
Jul 25 2007