Reputation: 5805
I have structures to describe position for various objects in my project. Some objects are indexed by two, or three, etc. indices.
In this simple example I show 3 types of position A
, B
and C
and they all
inherit from Position
which is empty. I inherit from Position
so that I can
pass these positions in functions that take Position
argument. The reason why
I don't use a single Position
structure is that I would have to put all the members
int a,b,c,d
in it, and for some objects most of the time I will just use a
and b
for example:
struct Position {
};
struct A : public Position {
int a,b,c,d;
};
struct B : public Position {
int a,b,c;
};
struct C : public Position {
int a,b;
};
The problem is, I have functions like this:
City &getCity(const Position &p) {
const B &pos = (const B &)p;
return rawSheets[pos.a].countries[pos.b].cities[pos.c];
}
Everything will be OK if I pass position of type B
to this function, but
what if I pass type A
? And I need to do that.
Upvotes: 1
Views: 83
Reputation: 17936
It seems like you actually want a hierarchy of position types, each more specific than the previous, somewhat like this:
struct Position1
{
int a;
};
struct Position2 : public Position1
{
int b;
};
struct Position3 : public Position2
{
int c;
};
struct Position4 : public Position3
{
int d;
};
That way, you can use a Position4
wherever a Position1
, Position2
or Position3
is needed, and the code will ignore the extra dimensions.
Upvotes: 1