Use of templates to avoid redudancy of code

Fawzi Mohamed fmohamed at mac.com
Tue Jun 3 22:38:34 PDT 2008


On 2008-06-03 20:20:16 +0200, Mael <mael.primet at gmail.com> said:

>> a simple compile time solution is to make the looping construct a
>> template, and the action a template parameter (either alias or char[]
>> to mixin if you need).
> To what does the "alias" correspond ? A function acting on the code?

this approach is like the delegate approach only that it is potentially faster.
An alias parameter to a template is a symbol that you pass to the template.
This symbol should be the delegate or function that executes the action.

void myAlgorithm(alias op)(args for the algorithm){
  for..
  for ..
    op();
}

the mixin is similar only that you pass a string and the string has 
access to all variables in the algorithm.
This is less safe, bur (form my experience with gdc) also potentially 
faster for very simple operations.

void myAlgorithm(char[] op_str)(args for the algorithm){
  for..
  for ..
    mixin(op_str);
}

op_str must be one (or more) complete statement (you need even the ";") 
and needs to be a string known at compile time.

Fawzi



More information about the Digitalmars-d-learn mailing list