why is `typeid` only half baked?

Or Dahan via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 6 08:38:03 PST 2015


When it comes to interfaces, apparently `typeid` always returns 
the type of the interface, An undocumented features, which is 
very misleading as for classes it returns the 'most derived type' 
(http://dlang.org/expression.html#TypeidExpression)

For example:

import std.stdio;

interface A {

}

class B : A {
     int y;
}

void foo(A a) {
     writefln("foo got 'a' of typeid(%s) which is really '%s'", 
typeid(a), a);
}

void main() {
     auto b = new B();
     writefln("Original scope got 'b' of typeid(%s) which is 
really '%s'", typeid(b), b);
     foo(b);
}

would print:

Original scope got 'b' of typeid(test.B) which is really 'test.B'
foo got 'a' of typeid(test.A) which is really 'test.B'

(notice that '%s' in the format correctly identifies 'a' to be of 
type 'B' in the same time that the typeid expression recognizes 
'a' as of type 'A')

Rewriting foo as:

void foo(A a) {
     writefln("foo got 'a' of typeid(%s) which is really '%s'", 
typeid(cast(Object)a), a);
}

solves the issue (Thanks to David Nadlinger)

I must say I find this very counter-intuitive as its VERY LIKELY 
to have an interface as the polymorphic instance and sometimes 
you would want to query its exact type.

Obviously `typeid` can infer that 'a' is really an `Object` and 
then infer that its of type `B` (just as the writefln managed to).
This leads me the conclusion that `typeid` is only half-baked and 
can be improved to support interfaces in a more intuitive manner.

Any reasons why it inherently can't be improved to do so?

Thanks.


More information about the Digitalmars-d mailing list