Re: Does object have function?
"Jim Langston" <tazmaster@rocketmail.com> wrote in
news:iacrrl$ah6$1@four.albasani.net:
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.
It is trivial to create a virtual function for a few functions. But I
would have to add every single function that could be interfaced.
This would just be one extra line for each function in the base class,
wouldn't it? Does not see so much extra work for me. A drawback is that
it is easy to accidentally break the system by changing the function
signatures so that the derived class methods are not proper overrides of
the base class methods any more. Some compilers provide extensions like a
'override' keyword to protect against this.
Alternatively, if performance is not very critical and you cannot or do
not want to spoil the base class with all those virtual functions, you
could use a home-grown lazy virtual dispatch, e.g.:
class Base {
public:
virtual ~Base() {}
virtual void Dispatch(const std::string& method) {}
};
class DerivedOne : public Base {
public:
void foo() { }
void bar() { }
virtual bool Dispatch(const std::string& method) {
if (method=="foo") {
foo();
} else if (method=="bar") {
bar();
} else {
// method not supported by this class
}
};
In reality, you will probably need to pass parameters of different types,
which is cumbersome in this approach. One could make use of some kind of
variant class for parameters.
Microsoft MFC is using message maps for something similar, but their
parameter nomenclature is very restricted thanks to the Windows SDK
conventions (a WPARAM and a LPARAM).
Cheers
Paavo