Forwarding or merging 'this' into a child class to aid chaining methods?

Gary Willoughby dev at nomad.so
Thu Mar 6 11:04:48 PST 2014


I'm trying to create methods across class hierarchies that can be 
chained nicely but i'm running into the problem that 'this' 
declared in a parent class only refers to that type. Is there a 
way i can get the following code to perform in the way i expect?

import std.stdio;

class Foo
{
	public auto foo()
	{
		return this;
	}
}

class Bar : Foo
{
	public auto bar()
	{
		return this;
	}
}

void main(string[] args)
{
	Bar bar = new Bar().bar().foo();
}

test2.d(21): Error: cannot implicitly convert expression ((new 
Bar).bar().foo()) of type test2.Foo to test2.Bar
Failed: 'dmd' '-v' '-o-' 'test2.d' '-I.'

How can i make the above marked 'this' refer to Bar when being 
called in a chain? When i call the methods like this each method 
call seems to implicitly convert 'this' into that method's 
containing class' instance, breaking the code and sometimes 
hiding child methods.



More information about the Digitalmars-d-learn mailing list