I have a structure containing lots (like, hundreds) of pointers. Each pointer is a different type, but they all inherit from a common base class --- let's call it Base. I'm using multiple inheritance. (This is all machine-generated, which is why it's weird.)
e.g.:
class Data {
Class1* p1;
Class2* p2;
Class3* p3;
...etc...
};
I want to call a method defined in Base on all of these. I can generate code like this:
void callFooOnData(Data* p)
{
if (p1) p1->Foo();
if (p2) p2->Foo();
if (p3) p3->Foo();
...etc...
}
The problem is, I've got lots and lots of these, of a billion different kinds of Data, and the above code ends up being very large and is affecting my footprint. So I'm trying to replace this with something smarter.
In C, I could simply take the address of the first structure member and the count, and do something like:
void callFooOnData(Data* p)
{
callFooOnObjects(&p1, 3);
}
But, of course, I can't do this in C++, because the structure members aren't a uniform type, and casting them to Base* may involve changing them, and this may involve changing the pointer, and because they're not a uniform type the pointers will have to be changed differently for each member, and I can't do that.
Is there a way to do something like this is C++? This is all machine generated code, so it doesn't have to be pretty, thankfully --- that shark has already been jumped --- but I do need it to be as portable as possible...
(I do have access to RTTI, but would like to avoid it if possible for performance reasons.)
Update:
So, as far as I can tell... you just can't do this in C++. Simply can't be done. I was misled by the fact that it's totally straightforward in C. In C++ you can only safely cast a pointer between two types in a class hierarchy if you have a well typed pointer to begin with, and of course, I don't.
So I'm going to have to change the underlying problem to avoid this: the solution I've come up with is to store every pointer in the structure twice, once in an array of Base* for iterating over, and once as a ClassWhatever* for calling methods on. Which sucks, of course, because it's going to double the size of the Data structure.
So if anyone would like to confirm this (I would love to be proven wrong), I will happily mark their answer as correct...