spir wrote: > Hello, > > > What is the common idiom to check whether the type of a given element is > what I expect? Seems that > typeof(e) == Type > is refused by the compiler, for any reason? I get > DeeMatch.d(237): Error: type string is not an expression > I'm using > typeof(e).stringof == "TypeName" > Is there a better solution? > > Also, how to override a class's field so that it is accessed according > actual/runtime type? (Like method dispatch.) void method (SuperType x) > {...access x.f...} If I don't define f in SuperType, then I get a compiler > error. If I do, then SuperType.f is accessed, not the field on actual > class of x. > > > Denis > -- -- -- -- -- -- -- > vit esse estrany ☣ > > spir.wikidot.com 1. I believe typeof(e) will give you the type of "e" not the type of the object e is pointing too. So for example
class A {} class B : A {} A a = new A(); B b = new B(); A a2 = new B(); typeof(a).stringof // A typeof(b).stringof // B typeof(a2).stringof // A I think there are methods in the Object class that gives you the name of the runtime type, but I have never checked. 2. When referencing SuperType you can only access the public members of SuperType (and its super/base types). In order to access the dervied class's members you need to reference it as the Derived. For example. class A { void a() {} } class B : A { void b() {} } class C : A { void c() {} } A d = new B(); d.a(); d.b(); // compile fail (cast(B) d).b(); (cast(C) d).c(); // fails at runtime I think as a rule the above is considered bad practice. If f does not exist in SuperType then you shouldn't be passing the function SuperType, you should be passing whatever type it is you are expecting that has f defined in it. The casts above get round it, but as I say, generally considered bad practice.