InstanceOf

Steven Schveighoffer schveiguy at yahoo.com
Mon Jun 24 08:46:01 PDT 2013


On Sun, 23 Jun 2013 11:29:10 -0400, Lemonfiend <lemon at fie.nd> wrote:

> On Sunday, 23 June 2013 at 15:15:16 UTC, Jacob Carlborg wrote:
>> On 2013-06-23 13:26, Lemonfiend wrote:
>>>> foreach (I i; array) {
>>>>    if (B b = cast(B) i) { ... }
>>>> }
>>>
>>> Thanks all 3 of you for the quick and identical answers. :)
>>>
>>> It had not occurred to me to use a cast for this, but indeed the
>>> language ref says the same:
>>> "In order to determine if an object o is an instance of a class B use a
>>> cast"
>>>
>>> It does a bit inelegant to me.. Or are casts simply extremely cheap?
>>
>> You can do something like this as well:
>>
>> if (i.classinfo is B.classinfo) { }
>>
>> But doing the cast is more efficient if you want to use the object of  
>> as the type you're checking for.
>
> Using the .classinfo is what I looked at before asking here.
> However, according to the specs:
> ".classinfo applied to an interface gives the information for the  
> interface, not the class it might be an instance of."
> So the i.classinfo and B.classinfo would be different?

1. Use typeid(i), not i.classinfo, classinfo is old-style.
2. Yes, typeid(i) will give you interface class info, or maybe even  
derived interface class info.  It's a simple indirection, whereas a cast  
must go through a pointer offset stored in the interface typeinfo in order  
to get true class info.
3. typeid(i) on one DLL may be different than typeid(i) on another.  It is  
not valid to compare the references directly

On 2, see test code:

http://dpaste.dzfl.pl/97f5866d

-Steve


More information about the Digitalmars-d-learn mailing list