python's "with" in D

downs default_357-line at yahoo.de
Wed Jul 25 04:20:04 PDT 2007


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



More information about the Digitalmars-d mailing list