instance_of in C++

This topic is 3918 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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?

Share on other sites
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.}

Share on other sites
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 :-)

Share on other sites
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

Share on other sites
Quote:
 Original post by fpsgamerThe 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.

Share on other sites
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.

Share on other sites
Only insomuch as dynamic_cast suffers from the same. C++ has no standard ABI, after all.

Share on other sites
Ahh yes, I forgot about that. Thanks for reminding me ;)

• 32
• 12
• 10
• 9
• 9
• Forum Statistics

• Total Topics
631352
• Total Posts
2999483
×