How to determine array-length (#
) at compile time from a complex code?
In my code, if I skimmed it, I can know how much array-size it is needed, but the related algorithm is scattering around many .h
/.cpp
.
(Sorry for an obscure title and introduction, I don't really know what the problem is called.)
A solid example (demo)
I want to create many type of relation 1:1 between many game objects.
Library code (static library)
GO.h
(game-object): store pointer to another-one.
class GO{//game object
public:
static const int numRelation=10; //#
GO* left[numRelation];
GO* right[numRelation];
public: GO(){
for(int n=0;n<numRelation;n++){
left[n]=nullptr;
right[n]=nullptr;
}
}
};
DB.h
(Database): It is a utility. It stores index of relation in userIndex
.
class DB{//database
int userIndex=-42;
public: DB(){};
public: DB(int us){userIndex=us;}
public: GO* getLeft(GO* g){return g->left[userIndex];}
public: void createRelation(GO* g1,GO* g2){
g2->left[userIndex]=g1;
g1->right[userIndex]=g2;
}
};
DBGenerator.h
(Database-Generator) :
It is a central system to help cooperation of many other sub-system.
It generates userIndex
for DB
.
class DBGenerator{//quite singleton
int indexCounter=0;
public: DB generate(){return DB(indexCounter++);}
};
User code (game-specific)
CageManager.h
has two 1:1 relation : hen-food
and hen-cage
.
FamilyManager.h
has one 1:1 relation hen-egg
.
class CageManager{
DB dbHenFood;
DB dbHenCage;
public: CageManager(DBGenerator* gen){
dbHenFood=gen->generate();
dbHenCage=gen->generate();
}
};
class FamilyManager{
DB dbHenEgg;
public: FamilyManager(DBGenerator* gen){
dbHenEgg=gen->generate();
}
};
The userIndex
will be reserved like this :-
I can add relation and query e.g. :-
int main() {
DBGenerator commander;
CageManager m1{&commander};
FamilyManager m2{&commander};
GO* hen=new GO();
GO* egg=new GO();
m2.dbHenEgg.createRelation(hen,egg);
GO* henGet=m2.dbHenEgg.getLeft(egg);
if(henGet==hen)std::cout<<"correct";
if(henGet!=hen)std::cout<<"wrong";
return 0;
}
Question
The above code works OK. (coliru demo, ideone backup)
However, as my game grows, I need more slot.
If the amount of slots exceeds 10, I have to edit the figure (const int numRelation=10
) in GO.h
manually.
Another trouble is that : if I want to create a new game,
I need to modify GO.h
to ensure that it will be enough (but not too much - waste memory) for the new game-logic.
How to make such variable (const int numRelation
) to always has a correct figure (3
in this test)?
Other note:-
- I want to avoid heap allocation, so the size of array have to be fixed.
- It is performance-critical, because the database is called excessively.
- I don't know if there is an elegant way.
From what I want,GO.h
will probably have to include those twomanager.h
.
It may break the whole architecture. (???)