Use of templates to avoid redudancy of code
Lutger
lutger.blijdestin at gmail.com
Tue Jun 3 03:15:18 PDT 2008
Mael wrote:
> Hello,
>
> I'm writing an algorithm that has, say, too possible behaviour depending
> on a switch. Since there are many imbricated loops, and the behaviour
> change is inside the loop, testing for the flag is time-consuming
>
> for( ....)
> for( .... )
> for( ... )
> {
> if( flag ) action_1 ;
> else action_2 ;
> }
>
> is there a clean way to use templates to generate the duplicate of the
> code like
>
> if( flag )
> {
> for(...) .... action1 ;
> }
> else
> {
> for(...) .... action2 ;
> }
If flag is a compile time constant, then you don't need no templates, just
this:
static if (flag) action_1
else action_2
The if is evaluated only at compile time.
If behavior is changed at runtime, it would depend a little on the rest of
the code, there are some different ways to implement if. For example as a
helper function:
void func(bool flag)
{
if (flag)
helper!(true)();
else
helper!(false)();
}
void helper(bool flag)()
{
for( ....)
for( .... )
for( ... )
{
static if( flag ) action_1 ;
else action_2 ;
}
}
More information about the Digitalmars-d-learn
mailing list