I have a simple setup with
class Container {
Handler h;
}
All the Container objects have a “warning()” method. I would like
to also have a way to output warnings from within the Handler object, but send
these warnings using the facilities of the containing object.
I do realize that holding a reference to the container in the contained object is odd (normally
the contained object should not know anything about it’s container). Now, in a language
with closures I would have done it like so (imaginary syntax):
h.set_warning_handler { | char* message |
this->warning(message)
}
but I am working in C++ and it’s not a place to use Apple dialect things like blocks.
What would be the preferred way to tackle this? Or just set that reference and forget about it?
C++11 has closures:
[&]specifies to capture the context by reference (needed to capturethis).(…)declares the argument list, and{…}the lambda’s body.Alternatively, you can make the
Handlerdependent on its container. This introduces quite strong coupling so it’s better to be avoided but sometimes it makes sense (e.g. if you cannot use C++11 features yet), and the strong coupling can be weakened by using an interface (the following uses late binding; sometimes, templates might be more appropriate):