digitalmars.D.learn - instanceof?
- Maxime Chevalier (8/8) Aug 01 2012 Getting started with D. I've been doing alot of googling trying
- Adam D. Ruppe (15/17) Aug 01 2012 I don't know if it is the best way, but I use the cast myself,
- Jonathan M Davis (4/16) Aug 01 2012 if(cast(Class)obj)
- Jacob Carlborg (6/8) Aug 01 2012 Or, to use the value after the cast:
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?
Aug 01 2012
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 }
Aug 01 2012
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
Aug 01 2012
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
Aug 01 2012