Use of templates to avoid redudancy of code

Chris Wright dhasenan at
Tue Jun 3 05:57:16 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

You've profiled and you've determined that checking that bool is 
expensive. One option is checking it at compile time:

void action1(args);
void action2(args);
template action(bool isActionOne)
	static if (isActionOne)
		alias action1 action;
		alias action2 action;

for (...)

// Or the same, but instead just hoping for inlining:
// global
const bool flag;
void action(args)
	static if (flag)

If the flag changes at runtime...

Change your functions from:
void foo(args)
	for (i = 0; i < some_really_huge_number; i++)
		if (flag) action1(args); else action2(args);

void foo(alias fn)(args)
	for (i = 0; i < some_really_huge_number; i++)

The vast majority of your methods would just pass on the alias template 
parameter. You'll still have to know about the flag and the functions 
wherever the flag might change, though.

More information about the Digitalmars-d-learn mailing list