Is there a way to determine at runtime if an object can use a method in C ++?
Perl has a UNIVERSAL :: can method that you can call on any class or object to determine if it can do something:
sub FooBar::foo {}
print "Yup!\n" if FooBar->can('foo'); #prints "Yup!"
Let's say I have a base class pointer in C ++ that can be any of several different derived classes, is there an easy way to do something similar to this? I don't want to touch anything in the other derived classes, I can only change the scope in the base class that calls the function and one derived class that supports it.
EDIT: Wait, this is obvious now (no matter the question), I could just implement it in a base that returns a number representing UNIMPLEMENTED, then check that it is not when you call it. I'm not sure why I was thinking about things in such a complex way.
I also thought that I would extract my class from another one that I implemented foo
and then see if dynamic casting to that class works or not.
source to share
C ++ doesn't have built-in runtime reflection. You are free to create your own reflection implementation in your class hierarchy. This usually includes a static map that is populated with a list of names and functions. You have to manually register each function you want and have consistency regarding the calling convention and function signature.
source to share
I believe the most correct way would be to use the typeid <> operator and get a reference to the type_info object, and then you could compare that (== operator) to the desired type_info for the datatypes you want to care about.
This doesn't give you method-level validation and requires you to build with RTTI enabled (I believe using typeid <> for an object that was instantiated without RTTI results, with "undefined" behavior), but you're there.
MSDN has an online link to get you started: http://msdn.microsoft.com/en-us/library/b2ay8610%28VS.80%29.aspx
source to share