B
bart van deenen
Hi
I have a pile of objects all derived from one baseclass, and I want to
have a generic function that an object can use to see if another
object is its superclass. Here's an example that does not work:
#include <stdio.h>
#include <typeinfo>
class A {
public:
void check(A *other) {
__typeof__(this) x = dynamic_cast<__typeof__(other)>(other);
if ( x ) printf("ok\n");
else printf("NULL\n");
}
};
class B : public A { };
class C: public B { };
class D: public A { };
int main()
{
D d;
A a;
C c;
printf("c.check(&a)\n");
c.check(&a);
printf("c.check(&d)\n");
c.check(&d);
}
g++ -frtti -Wall -o main main.cpp
c.check(&a)
ok
c.check(&d)
ok
but C does not inherit from D!
I now know more about the function of the __typeof__ operator, so I
understand why it doesn't work. But how would you do this? Is there an
elegant way?
I have a pile of objects all derived from one baseclass, and I want to
have a generic function that an object can use to see if another
object is its superclass. Here's an example that does not work:
#include <stdio.h>
#include <typeinfo>
class A {
public:
void check(A *other) {
__typeof__(this) x = dynamic_cast<__typeof__(other)>(other);
if ( x ) printf("ok\n");
else printf("NULL\n");
}
};
class B : public A { };
class C: public B { };
class D: public A { };
int main()
{
D d;
A a;
C c;
printf("c.check(&a)\n");
c.check(&a);
printf("c.check(&d)\n");
c.check(&d);
}
g++ -frtti -Wall -o main main.cpp
c.check(&a)
ok
c.check(&d)
ok
but C does not inherit from D!
I now know more about the function of the __typeof__ operator, so I
understand why it doesn't work. But how would you do this? Is there an
elegant way?