typeid() broken for interfaces?

Paulo Pinto pjmlp at progtools.org
Tue Dec 4 04:30:28 PST 2012


On Tuesday, 4 December 2012 at 12:26:53 UTC, Jacob Carlborg wrote:
> On 2012-12-04 09:22, Maxim Fomin wrote:
>
>> 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));
>> }
>
> You get a segmentation fault since both "i" and "o" are null.
>
>> 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
>
> You cannot really get an instance of an interface without 
> having a class implementing it. That is, without inserting any 
> explicit casts, which works:
>
> interface I { }
>
> class A { }
>
> void main()
> {
>     A a = new A;
>     I i = cast(I) a;
>     Object o = cast(Object)i;
>     writeln(typeid(a)); // A
> }
>
>> 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.
>
> I don't understand why it wouldn't be safe to allow implicit 
> casts of interfaces to Object.
>
> If I want to call toString, why should I need to insert an 
> explicit cast to Object just because I have an interface?

If you want to call toSring, it should be part of the interface 
specification, as simple as that.

Interfaces are like contracts which state what is to be expected 
of a certain type.

--
Paulo



More information about the Digitalmars-d mailing list