Hello,
I convert a Python/Qt program (PyQt) in C++/Qt.
The programmer has used the duck typing of Python, thus I would like to have
duck typing in C++, in fact exactly what is described in the "best answer"
at the following address:
http://stackoverflow.com/questions/289176/how-is-duck-typing-different-from-
the-old-variant-type-and-or-interfaces
(the "best answer" is the second post of the page, the one with a green
sign).
Is it possible in C++?
yes, and it is also possible in C, but the "ideal" strategy will differ.
also, IIRC, Boost may offer something like this, if this is relevant.
but, other potential strategies:
using RTTI:
merits: reasonably simple and straightforward in C++, meshes well with
C++ style, ...
downside: depends on classes and is subject to compiler issues (may be
disabled by command-line options, or require a command-line option to
enable), and may potentially have drawbacks related to overhead, on some
systems (namely Windows), it may break violently across arbitrary
borders (say, if you make a DLL and then use the DLL from an EXE, the
RTTI may not actually work).
http://en.wikipedia.org/wiki/RTTI
using tagged references:
merits:
may be reasonably efficient;
very commonly used in implementing VMs (dominant strategy);
relatively C-friendly;
integers or floating point values may be directly encoded into
references (sometimes called fixnum and flonum);
....
downside:
may be more awkward to use (depending on details, requiring much added
manual boxing/unboxing/bookkeeping);
bit-twiddly and magic numbers.
using "magic pointers" (where one has a raw pointer, and types are
identified based on the pointed-to object or memory-address):
merits:
can be made fairly easy to use (depending on implementation details,
dynamic types in C++ can be made to have a "look and feel" almost as if
one was them in a dynamically-typed language);
are also relatively C friendly;
generally much easier to manage than tagged references;
it is often easier to extend the type-system in an ad-hoc manner;
may be made cast-compatible with struct or class pointers;
....
downside:
potentially less efficient and more complex to implement than tagged
references;
they are a less well-known strategy;
generally, fewer bits can be afforded to fixnum and flonum types (mostly
an issue on 32-bit systems).
or such...