Jump to content
  • Advertisement
Sign in to follow this  
rozz666

instance_of in C++

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

If you intended to correct an error in the post then please contact us.

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 this post


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

Share this post


Link to post
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 this post


Link to post
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 this post


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

Share this post


Link to post
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!