Re: Does object have function?
On Oct 29, 12:01 am, "Jim Langston" <tazmas...@rocketmail.com> wrote:
What I am trying to accomplish: I have a map of polymorphic objects and
these objects may have certain methods defined or not. If the instance=
has
the method then I want to call it, otherwise not.
Are these methods all of same signature (e.g. one "int" param)? If so,
then you can do this:
struct base;
typedef int (*pFunc)(base&, int);
struct base
{
virtual pFunc GetFunc(int whichOne) const = 0;
};
struct derived : public base
{
virtual pFunc GetFunc(int whichOne) const
{
return (7 == whichOne) ? &derived::func : NULL;
}
static int func(base&, int) {/*...*/ return 0; }
};
//and then
void f(base& b)
{
pFunc f = b.GetFunc(7);
if (f)
f(b, 1);
}
(That's +/- the same as Paavo's suggestion with message maps, but you
choose your function signature, and, GetFunc allows you to choose//
refuse giving out pFunc at run-time.)
If your functions are of varying signatures, then I would go for mix-
in inheritance and dynamic_cast is better (Fooer example here). In
fact, I see nothing wrong with Fooer example at all. Inspecting if an
object has a particular interface isn't all that bad, after all.
( Inspecting for a lot of of them, which you seem to be doing,
however, smells a bit bad ;-) ).
Goran.