On Sep 30, 11:59 am, Albert Zeyer <albert.z...@rwth-aachen.de> wrote:
Basically, I want to do the following:
bool operator==(const Base& o1, const Base& o2) {
return &o1.func == &o2.func;
}
How can I do this? I don't want to add any RTTI to the project as
it is
not really needed here (because in my case, it's enough to just
compare
the vtable).
...
That is what I also found out after some research. I thought there is
perhaps some trick to do this.
Right now, I have solved this by doing the following:
template <typename _dst, typename _src>
_dst* simple_dyn_cast(_src* ptr) {
_dst tmp;
if(memcmp(ptr, &tmp, sizeof(_src)) == 0) { // compare vtable
return (_dst*)ptr;
}
return NULL;
}
template <typename _dst, typename _src>
_dst* simple_dyn_cast(_src* ptr, _dst* base) {
if(memcmp(ptr, base, sizeof(_src)) == 0) { // compare vtable
return (_dst*)ptr;
}
return NULL;
}
That works as long as the Base class contains a set of virtual
functions
and no member variables. (At least it seems to work on various GCC
versions under varios systems and on MSVC++.)
These functions may in fact "work", but I could not imagine using them
in any C++ program. The code of these functions is as fragile as it is
opaque - and makes all sorts of unwarranted assumptions about the
inner workings of classes. In short, these routines are "hacks". And
completelyy unnecessary hacks at that. These routines could be safely
and cleanly implemented if only they relied on C++'s built-in facility
for testing the type of a polymorphic object.
[ comp.lang.c++.moderated. First time posters: Do this! ]