www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - letting D generate functions that look alike

reply "Saaa" <empty needmail.com> writes:
As the subject says, I would like D to generate functions from a template or 
something.

I have a (elaborate) function which I have to copy a few times with only 
minor changes.
I could make the function variadic, but this would be slower.
Can I let D create the functions for me?

The changes between the functions aren't complexer than:

int add_1(int num){
  int i;
  i=num+1;
  return i;
}

int add_2(int num){
  int i;
  i=num+2;
  return i;
}
Mar 20 2008
parent reply BCS <ao pathlink.com> writes:
Reply to Saaa,

 As the subject says, I would like D to generate functions from a
 template or something.
 
 I have a (elaborate) function which I have to copy a few times with
 only
 minor changes.
 I could make the function variadic, but this would be slower.
 Can I let D create the functions for me?
 The changes between the functions aren't complexer than:
 
 int add_1(int num){
 int i;
 i=num+1;
 return i;
 }
 int add_2(int num){
 int i;
 i=num+2;
 return i;
 }

|int add(int inc)(int num){ | int i; | i = num+inc; | return i; |} | |add!(1)(val); |add!(2)(val); I have done functions with bool template parameters and then static if inside. If you want clean names for them you can use aliases alias add!(1) add_1; alias add!(2) add_2;
Mar 20 2008
parent "Saaa" <empty needmail.com> writes:
Thanks,
I'll try this on my functions (and read up on templates. Never used those 
before.. exciting :)

 |int add(int inc)(int num){
 |  int i;
 |  i = num+inc;
 |  return i;
 |}
 |
 |add!(1)(val);
 |add!(2)(val);

 I have done functions with bool template parameters and then static if 
 inside. If you want clean names for them you can use aliases

 alias add!(1) add_1;
 alias add!(2) add_2;

 

Mar 20 2008