Thread overview | ||||||
---|---|---|---|---|---|---|
|
August 02, 2012 instanceof? | ||||
---|---|---|---|---|
| ||||
Getting started with D. I've been doing alot of googling trying to find out what's the best way to check if an object is an instance of some class. So far, I found you could do: if (typeid(obj) == typeid(Class)) doSomething(); or: if (cast(Class)obj) doSomething(); These both seem a little clumsy, however. Is there a better way to do this? |
August 02, 2012 Re: instanceof? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Maxime Chevalier | On Thursday, 2 August 2012 at 01:59:02 UTC, Maxime Chevalier wrote: > These both seem a little clumsy, however. Is there a better way to do this? I don't know if it is the best way, but I use the cast myself, though I like using a little wrapper: T instanceof(T)(Object o) if(is(T == class)) { return cast(T) o; } Then, you can say if(object.instanceof!SomeClass) { // use } or if(auto some_class = object.instanceof!SomeClass) { // use some_class } |
August 02, 2012 Re: instanceof? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Maxime Chevalier | On Thursday, August 02, 2012 03:59:01 Maxime Chevalier wrote:
> Getting started with D. I've been doing alot of googling trying to find out what's the best way to check if an object is an instance of some class. So far, I found you could do:
>
> if (typeid(obj) == typeid(Class)) doSomething();
>
> or:
>
> if (cast(Class)obj) doSomething();
>
> These both seem a little clumsy, however. Is there a better way to do this?
if(cast(Class)obj)
is the canonical way to do it.
- Jonathan M Davis
|
August 02, 2012 Re: instanceof? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jonathan M Davis | On 2012-08-02 05:06, Jonathan M Davis wrote: > if(cast(Class)obj) > > is the canonical way to do it. Or, to use the value after the cast: if (auto foo = cast(Class) obj) // use foo -- /Jacob Carlborg |
Copyright © 1999-2021 by the D Language Foundation