In brief: From a C++ base-class pointer which points to an instance of a derived class, how can one determine at run-time whether a non-pure virtual functio
Perhaps this helps. It alone doesn't answer your original question, but you can augment your base class (here, Foo) to use a certain interface if it is supplied or use a default method otherwise.
#include
struct X {
virtual void x () = 0;
};
struct Y {
virtual void y () = 0;
};
struct Foo {
virtual ~ Foo () {}
bool does_x () {
return NULL != dynamic_cast (this);
}
bool does_y () {
return NULL != dynamic_cast (this);
}
void do_x () {
dynamic_cast (*this) .x ();
}
void do_y () {
dynamic_cast (*this) .y ();
}
};
struct foo_x : public Foo, public X {
void x () {
std :: cout << __PRETTY_FUNCTION__ << std :: endl;
}
};
struct foo_y : public Foo, public Y {
void y () {
std :: cout << __PRETTY_FUNCTION__ << std :: endl;
}
};
struct foo_xy : public Foo, public X, public Y {
void x () {
std :: cout << __PRETTY_FUNCTION__ << std :: endl;
}
void y () {
std :: cout << __PRETTY_FUNCTION__ << std :: endl;
}
};
void test (Foo & f)
{
std :: cout << &f << " "
<< "{"
<< "X:" << f .does_x () << ", "
<< "Y:" << f .does_y ()
<< "}\n";
if (f .does_x ())
f .do_x ();
if (f .does_y ())
f .do_y ();
}
int main ()
{
foo_x x;
foo_y y;
foo_xy xy;
test (x);
test (y);
test (xy);
}