Automatic method overriding in sub-classes

Tofu Ninja via Digitalmars-d digitalmars-d at puremagic.com
Mon Oct 26 17:27:44 PDT 2015


On Tuesday, 27 October 2015 at 00:07:36 UTC, Ali Çehreli wrote:
> I don't understand all uses of the request but typeid() returns 
> a TypeInfo reference, which is about the actual type of an 
> object. The following change produces the expected output in 
> this case (except, it has the added module name):
>
> void bar() { writeln(typeid(this).name); }
>
> The output:
>
> A
> deneme.A
> B
> deneme.B
> A
> deneme.B
>
> Ali

Here is another example

void main()
{
	A a = new A();
	a.foo(); // prints nothing
	a.bar(); // prints nothing

	B b = new B();
	a.foo(); // prints X
	b.bar(); // prints X

	A c = new B();
	a.foo(); // prints nothing
	c.bar(); // prints X, <--- main advantage
}

enum uda;

class A
{

	void foo(this T)()
	{
		import std.traits : hasUDA;

		auto t = cast(T) this;
		foreach(s; __traits(allMembers, T))
		{
			static if(hasUDA!(mixin("t." ~ s),  uda))
			{
				writeln(s);
			}
		}
	}

	void bar(auto override this T)()
	{
		auto t = cast(T) this;
		t.foo();
	}
}

class B : A
{
	@uda int x;
}


More information about the Digitalmars-d mailing list