instance_of in C++

Started by
6 comments, last by Hodgman 16 years, 7 months ago
Since there is not instance_of operator in C++, I was wondering if my approach is correct: template <class T, class Ty> inline bool instance_of(const Ty& ty) { return dynamic_cast<T *>(const_cast<Ty *>(&ty)); }; This can be used llike this: if (instance_of<SomeDerivedType>(someObject)) // do something.... Is it OK to specify only 1 argument in a template and get the other from parameter type?
Advertisement
Yes, it's permissible to omit an argument. However, the results of your const_cast are undefined in the universal case, and the cast itself is useless because you can use:

template <class T, class Ty>inline bool instance_of(const Ty& ty){return dynamic_cast<const T *>(&ty);};


In the end, I feel this approach is useless when compared to the usual C++ idiom, which has the advantage of also providing a named variable of the correct type pointing to the instance:

if (SomeDerivedType* derived =     dynamic_cast<SomeDerivedType*>(&someObject)){  // Do something with the 'derived' pointer here.}

Yeah, you're right. So actually my instance_of is equivalent to dynamic_cast, the only difference being that the first returns bool.

I'll throw it away :-)
The typeid() operator does exactly what you want. This requires you use a compiler that supports RTTI (run time type information) ... pretty much any modern compiler does.

click
Quote:Original post by fpsgamer
The typeid() operator does exactly what you want.


If he wants to exclude subclasses, then yes.

Otherwise no. Given that his implementation didn't exclude subclasses, and his accepted simpler alternative doesn't either, I'd be rather wary of making the assertion that it's exactly what he wants.
Also, different compilers can return different results using typeid.

So if your entire project is built on the one compiler it will be fine, but if you have a DLL built by someone else you might get some unexpected results.
Only insomuch as dynamic_cast suffers from the same. C++ has no standard ABI, after all.
Ahh yes, I forgot about that. Thanks for reminding me ;)

This topic is closed to new replies.

Advertisement