2

In Perl, there is a UNIVERSAL::can method you can call on any class or object to determine if it's 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 don't 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. I'm 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jake
  • 211
  • 3
  • 5

4 Answers4

7

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
  • 54,973
  • 13
  • 116
  • 224
5

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
  • 363,768
  • 54
  • 674
  • 675
3

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 consistency as to the calling convention and function signature.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eclipse
  • 44,851
  • 20
  • 112
  • 171
2

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
  • 319
  • 1
  • 2