In this problem, assume that we have handled all pointers in a nice, careful manner - to prevent question bloat I don't want to include my cleanup code here!
Let's say we have two classes, Foo
and Bar
with class definitions as follows:
class Foo
{
public:
Foo();
void fooFn();
};
class Bar
{
public:
Bar();
void barFn();
};
Assume that it is necessary that Foo
and Bar
have no inheritance relationship, but we need to call both fooFn
and barFn
in response to some stimulus. We can create a controller class with a container from which to call fooFn
and barFn
on specific instances of Foo
and Bar
- a static std::vector
for example - but we run into an issue: pointers to member functions of Foo
and Bar
instances are of different types.
By using a static vector< std::function<void()>* >
in the controller class, we can make a workaround. Foo
and Bar
instances can have a function which adds pointers to the vector through a lambda function which captures this
:
void Foo::registerFnPointer()
{
ControllerClass::function_vector.push_back( new [this](){ return this->fooFn(); } );
}
I have tested this method, and it appears to work without any problems. That said, I am concerned about the issues that could be caused by circumventing the type difference mentioned before... Am I worrying over nothing? Is there a better way to accomplish equivalent functionality?