let’s say I have the following loops:
for(int i=left; i < right; i++) {
for(int j=top; j < bottom; j++) {
if(tilesMap[i][j])
(tilesMap[i][j])->Draw(window) ;
}
}
and
for(int i=left; i < right; i++) {
for(int j=top; j < bottom; j++) {
(tilesMap[i][j])->Draw(window) ;
}
}
Is there any way I can make this “generic”, ie if some boolean is true, I will call the first code segment, if not I’ll call the second code segment.
I obviously could do a test before the loop and branch on the right loop, but then I have to duplicate the loop “header” and the instruction inside too, and change it twice every time I change the code inside the loop. The other solution is to do a test inside the lopp at every iteration, but this would make way too many tests at runtime.
Is there any other way I can do this? thanks
EDIT: this is just a question for my knowledge, I’m perfectly fine with duplicating my code for such small amount
You can use a pointer to a function(i,j).
Or an object. If you use C++, you can do it object oriented way i.e. with a virtual method and inheritance. It will need a lot of source lines, but it will be clean code. 🙂