On Wednesday, 20 November 2019 at 13:46:07 UTC, Jacob Carlborg
wrote:
On Wednesday, 20 November 2019 at 10:05:11 UTC, zoujiaqing
wrote:
import std.stdio;
class A
{
this(T)(T t)
{
}
void write()
{
T _this = cast(T) this;
writeln(this.v);
}
}
class B : A
{
string v = "hello";
}
void main()
{
auto b = new B;
writeln(b.write()); // print hello
}
You can use a template this parameter [1], like this:
import std.stdio;
class A
{
void write(this T)()
{
T self = cast(T) this;
writeln(self.v);
}
}
class B : A
{
string v = "hello";
}
void main()
{
auto b = new B;
b.write();
}
[1] https://dlang.org/spec/template.html#template_this_parameter
--
/Jacob Carlborg
I'm not the OP but a lurker, and this is new to me, I mean in
your example you're accessing a member "v" which wasn't defined
in the Parent class.
So if someone creates something like this:
class C : A{
string x = "world"; // x instead of v
}
Not the "x" instead of "v", of course it will only get an
compiler error if that function is called in by "C" object.
I think this is a powerful and weird feature at the same time,
because some could write a code like this:
import std.stdio;
class A{
void write(this T)(){
T self = cast(T) this;
writeln(self.v);
}
void write2(this T)(){
T self = cast(T) this;
writeln(self.x);
}
}
class B : A{
string v = "hello";
}
class C : A{
string x = "world";
}
void main(){
auto b = new B;
b.write();
auto c = new C;
c.write2();
}
This is a different way of designing things, do people use this
often?
Matheus.