Let’s say I have a C++ interface
class Iface
{
public:
virtual ~Iface () {}
virtual void foo () = 0;
virtual void bar () = 0;
};
And I have some set of classes that needs to expose that on one side and implement it off somewhere else. I find that quite commonly I end up with a bunch of classes in the middle which essentially do something like this:
class InTheMiddleSomewhere
: public Iface // amongst other things
{
public: // Iface
virtual void foo () { if (impl) impl->foo (); }
virtual void bar () { if (impl) impl->bar (); }
private:
IfaceImpl* impl;
};
Which gets tiresome to write and maintain as the interfaces expand, proliferate and change.
Q: Is there a better (more or less automatic) way to implement a pass through for a complete interface than coding all that “if (impl) impl->…” stuff by hand?
You can bind the call into a function object, and then just pass through the function object (rather than making a delegate call for each member function of the interface).
Consider the following:
Now I have some implementation of I:
So I can call x, y and zs function like:
or I can bind a call to a method of the I interface as follows:
and then later:
This works even if x, y and z are different classes, as long as they are derived from I.