On Thursday, 6 March 2014 at 19:04:50 UTC, Gary Willoughby wrote:
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.
public auto foo(this T)()
{
return cast(T) this;
}
http://dlang.org/template.html#TemplateThisParameter