typeid() broken for interfaces?

foobar foo at bar.com
Tue Dec 4 04:25:34 PST 2012


On Tuesday, 4 December 2012 at 07:38:31 UTC, Maxim Fomin wrote:
> On Monday, 3 December 2012 at 23:53:26 UTC, deadalnix wrote:
>> On Monday, 3 December 2012 at 21:53:47 UTC, Walter Bright 
>> wrote:
>>> I really don't know what issue you're trying to solve here. 
>>> The typeid's work fine - and interfaces are not objects. 
>>> Having the typeid for an interface be an object means you 
>>> cannot compare typeids of one interface to another interface.
>>>
>>
>> You can't instantiate interface. So an underlying type MUST 
>> exist. The whole point of typeid on expression is to discover 
>> what is the dynamic type of things, otherwize you'd be using 
>> typeid(type) not typeid(expression).
>
> You cannot create interface instance with new operator because 
> interface object is not valid until it is actually some class 
> instance. But this does not mean neither that typeid operator 
> for interfaces should return dynamic type nor that interface 
> can be implicitly converted to Object - because interface 
> instance may be invalid:
>
> import std.stdio;
>
> interface I { }
>
> void main()
> {
> 	I i;
>         // should be implicitly converted
> 	Object o = cast(Object)i;
> 	writeln(typeid(o));
> }
>
> and because presence of interface does not necessarily mean 
> that some class has implemented it.
>
> This makes casting interfaces to object unsafe operation that 
> better should require explicit cast.

The above is a perfectly safe conversion.
The variable i is _a reference_ to instance of I. since it was 
not assigned any class instance that implements I, it is 
initialized as _null_.
In the example above: (o is null && typeid(o) == typeid(Object))



More information about the Digitalmars-d mailing list