views:

192

answers:

4

In Perl, there is a UNIVERSAL::can method you can call on any class or object to determine if its able to do something:

sub FooBar::foo {}
print "Yup!\n" if FooBar->can('foo'); #prints "Yup!"

Say I have a base class pointer in C++ that can be any of a number of different derived classes, is there an easy way to accomplish something similar to this? I dont want to have to touch anything in the other derived classes, I can only change the area in the base class that calls the function, and the one derived class that supports it.

EDIT: Wait, this is obvious now (nevermind the question), I could just implement it in the base that returns a number representing UNIMPLEMENTED, then check that the return is not this when You call it. Im not sure why i was thinking of things in such a complicated manner.

I was also thinking i would derive my class from another one that implemented foo then see if a dynamic cast to this class worked or not.

+7  A: 

If you have a pointer or reference to a base class, you can use dynamic_cast to see which derived class it is (and therefore which derived class's methods it supports).

ChrisW
+3  A: 

C++ does not have built in run-time reflection. You are perfectly free to build your own reflection implementation into your class hierarchy. This usually involves a static map that gets populated with a list of names and functions. You have to manually register each function you want available, and have consistancy as to calling convention and function signature.

Eclipse
+5  A: 

If you can add methods to the base class, you can add a virtual bool can_foo() {return false;} and override it in the subclass that has foo to return true.

sepp2k
+2  A: 

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 data types you wish to care about.

This doesn't give you method-level inspection, and does require that you've built with RTTI enabled (I believe that using typeid<> on an object that was built without RTTI results with "undefined" behavior), but there you are.

MSDN has an online reference to get you started : http://msdn.microsoft.com/en-us/library/b2ay8610%28VS.80%29.aspx

ted_j