In working on Kira3, I was playing around with the C++ compiler and looking for a good way of implement Kira's duck typing. I was hoping (as it has been a few years of direct C++ programming) that I could use multiple inheritance for member access under multiple types. Alas, I have failed so far...
The ideal code would look like:
class WithX { public: int x; };
class WithY { public: int y; };
class WithZ { public: int z; };
class Point2D : public WithX, public WithY { };
class Point3D : public WithZ, public WithX, public WithY { };
void ZeroOut(Point2D * p) { p->x = 0; p->y = 0; };
int _tmain(int argc, _TCHAR* argv[])
{
Point3D* p = new Point3D();
p->x = 1;
p->y = 1;
p->z = 1;
ZeroOut(p);
return 0;
}
However, it throws a typing error at the invocation of ZeroOut(p). This is ultra sad face. I can force it work by creating a type tower. In the above example, I could change class Point3D : public WithZ, public WithX, public WithY { }; to class Point3D : public Point2D, public WithZ { };
The problem now is when I have structures that overlap. I would either throw an error that would be a pain to solve in kira code, or I have the compiler do something different. I tried
class Point3D : public Point2D, public WithZ, public WithX, public WithY { };
with the hope of the compiler combining them, but this gives ambiguous access to member variables. This can be fixed by replicating writes to the ambiguous member variables, and this could be a solution during my compilation phase. This solution requires more memory.
Any ideas how to solve this without a memory loss?
Or, is there a way to cast variables to multiple types? like
(WithX,WithY *)p