Page 1 of 1

Using a clock of code in two places

Posted: Wed Jul 11, 2012 12:52 pm
by Adversus
I have some like

Code: Select all

 
s32 numPasses = 1;
if( something )
   numPasses = 2;
for(int i=0; i<numPasses; i++ ) 
{ 
   if( i == 1 )
       DoSomething();
 
   MainSomething();
}
 
Where I want to be able to change MainSomething. I don't want to use a switch statement or a virtual function or a pointer to a function due to performance and readibility issues.

Basically I would like to be able to make the top and bottom parts a macro as I seem to remember some code used for scripting that did something similar but can't remember quite how it worked. I tried using a multi-line macro but just got compilation errors.

Does anyone have any other ideas?

Re: Using a clock of code in two places

Posted: Wed Jul 11, 2012 8:52 pm
by REDDemon
Use a virtual function. Its perfromance impact is neglictable. Todays all memory is allocated virtually. So it comes almost for free. Virtual function calls
are not bottlenecks at all.

Never use Macros.

a C programmer would tell you to use a pointer to a function, but that will have the same cost of virtual call.(didn't tested. Just readed)

if you want to do that just because you don't want to write the same piece of code zillion times:
1) bad design, rethink your code maybe help you to improve reusability of the code
2) maybe templates can help, not Macros. (but if every function does something different would be really hard using templates)
3) use functions of your IDE that can help you to copy-past similiar part of code.

anyway point 1 is most important, if you later you find some error in your code you have to replicate the change in ever place you pasted that code. Good design help
to avoid that

Re: Using a clock of code in two places

Posted: Tue Jul 31, 2012 11:41 pm
by Adversus
Thanks.

In the end I only needed to do this 3 times rather than the numerous times I thought I would have to do it (due to a change in the technical requirement) so it became a non-issue.