Re: duct typing and interface in C++
On Sun, 24 Jul 2011 20:23:59 +0200, TP wrote:
In fact, I would like to have duck typing exactly as in Python:
Then use Python.
in Python
there is no need to have an inheritance relation between the interface and
the class Daffy.
That's because Python is a dynamically-typed language, where method
look-up is done at run time.
In my previous post, I pointed to an example with no such inheritance
relation:
http://stackoverflow.com/questions/289176/how-is-duck-typing-different-from-
the-old-variant-type-and-or-interfaces
Note that the code given there isn't valid C++.
I would like to have a construction where the following affectation is
possible:
InterfaceDuck * d = new Daffy;
without inheritance relation between InterfaceDuck and Daffy.
The fact that Daffy has a method Quack() as InterfaceDuck should be enough
to allow that.
But perhaps there is no means to do that in C++?
Well, not unless you consider using C++ to write a dynamically-typed
language such as Python to be a solution.
If, for some reason, you can't make specific classes derive from
InterfaceDuck, you can use a template to create a wrapper or proxy for
such classes, e.g.:
template <class T>
class ProxyDuck : public InterfaceDuck {
T& ref;
ProxyDuck(T& ref) : ref(ref) {}
void quack() { ref.quack(); }
};