Error: 'this' is only defined in non-static member functions, not parse

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jan 17 12:12:51 PST 2012


On Tue, Jan 17, 2012 at 08:25:28PM +0100, Timon Gehr wrote:
[...]
> In other words, non-static nested classes can reference non-static
> fields of the enclosing class. [...]
[...]
> void main() {
>     auto a = new A;
>     auto b = a.new B; // construct an 'A.B' with 'a' in implicit
> 'outer' field
>     a.x = 100;
>     b.echo(); // writes '100'
> }
> 
> This is probably one of the more obscure features of D. =)
[...]

It totally makes sense though. In some of my past C++ projects, I've had
to use the inner class idiom quite often. Of course, it's not directly
supported by the language so I ended up writing lots of little nested
classes like this:

	class outer {
		...
		class inner1 {
			outer *ctxt;
			...
			inner1(outer *c) : ctxt(c) {}
		};
		...
		class inner2 {
			outer *ctxt;
			...
			inner2(outer *c) : ctxt(c) {}
		};
		...
		void f() {
			...
			inner1 *helper1 = new inner1(this);
			register_callback(helper1, ...);
			...
			inner2 *helper2 = new inner2(this);
			register_callback(helper2, ...);
			...
		}
	};

After a while, it just got really really tedious to keep writing the
same boilerplate code over and over again. In D, a lot of that
redundancy can be gotten rid of (no need for explicit outer pointers in
the inner classes, eliminate ctor parameters), just because (non-static)
inner classes automatically get an outer pointer, and you can just
instantiate them with:

	auto helper1 = this.new inner1;

But D lets you do even better. Instead of creating an inner class, you
can just pass a delegate to do what needs to be done:

	void f() {
		...
		register_callback((args) { this.state1++; }, ...);
		register_callback((args) { this.state2++; }, ...);
		...
	}

Much more readable, and much less room for bugs to hide in.


T

-- 
"Maybe" is a strange word.  When mom or dad says it it means "yes", but when my big brothers say it it means "no"! -- PJ jr.


More information about the Digitalmars-d-learn mailing list