Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to determine at runtime if an object can do a method in C++?

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.

like image 436
Jake Avatar asked Nov 25 '25 23:11

Jake


2 Answers

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).

like image 107
ChrisW Avatar answered Nov 28 '25 16:11

ChrisW


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.

like image 35
sepp2k Avatar answered Nov 28 '25 16:11

sepp2k