typeid() broken for interfaces?

Maxim Fomin maxim at maxim-fomin.ru
Tue Dec 4 00:22:35 PST 2012


On Monday, 3 December 2012 at 15:52:24 UTC, Jacob Carlborg wrote:
> On 2012-12-03 16:51, Jacob Carlborg wrote:
>
>> Because Object is the root of the class hierarchy. That's how 
>> it works
>> in Java, for example. It's just because of these COM 
>> interfaces, that
>> are not D interfaces, that we have this behavior.
>
> Note, I'm not saying that an interface should be implicitly 
> converted to any class, only to Object.

And what happens if nobody implements an interface?

import std.stdio;

interface I { }

class A { }

void main()
{
	I i;
	// assume this is implicit
	Object o = cast(Object)i;
	writeln(typeid(o));
}

Safe conversion class to interface requires two conditions:
1a) that class implements interface
1b) if you try to use interface variable, it must be an allocated 
class instance

Safe conversion to Object requires:
2a) somebody in class hierarchy implements interface
2b) interface instance is actually allocated class instance

It is possible to check 1a) but impossible in general case to 
check 2a). Also the first is design feature while the second is 
design abuse.

And if there is need for getting runtime type of interface 
through typeid() it is always possible to use cast:

import std.stdio;

interface I { }

class A : I { }

void main()
{
	A a = new A;
	I i = a;
	Object o = cast(Object)i;
	writeln(typeid(o)); // A
}


More information about the Digitalmars-d mailing list