Down Hierarchy with Non-Polymorphic Types

It is strict in C.

Say you are given one basic structure and two other derived structures. These derived structures are not produced in the classical sense (i.e.: A: B), but rather contain only structures of the base type. So, if struct A is the base, and B is one of 2 derived structures, B will have a member of type A. Like this:

struct A {
     // blah blah...
};

struct B {
     A part_a;
     // more stuff...
}

struct C {
     A part_a;
     // SO MUCH STUFF
}

Say you have an A_downcast_B function, something like this:

B * A_downcast_B(A * a)
{
     // downcast the A* here somehow
}

You want this function to return, 0or -1if you were 'a'not able to flush down to the type structure B. So, for example, if a "derived" type structure Chad a pointer to a type of type A*, and this pointer was passed to this function, the function would return 0, -1or null.

? , .

+3
1

- struct A. , - , , "" .

struct RTTI {
  const char *typename;
  // etc.
};

struct A {
  const RTTI *rtti;
  // rest of A
};

struct B {
  A part_a;
  ...
};

const RTTI RTTI_B = {"B"};

struct C {
  A part_a;
  ...
};

const RTTI RTTI_C = {"C"};

void make_B(B *b)
{
  b->part_a.rtti = &RTTI_B;
  // make the rest of B
}

void make_C(C *c)
{
  c->part_a.rtti = &RTTI_C;
  // make the rest of C
}

B * A_downcast_B(A * a)
{
   return (a->rtti == &RTTI_B) ? (B*)a : NULL;
}

, ++ dynamic_cast, . , , - vtable.

+8

Source: https://habr.com/ru/post/1788895/


All Articles