what language's feature is suitable for similar functions with only several different lines?
I have a programming problem and I thought it for several days, but still without good solutions.
There are several big, long and similar functions, in which only several lines are different. For example:
void bigfunc(){
//blabla..
int i, j, k;
//only this part is different
{ i++ } //in bigfunc1;
{ i++, j++} //in bigfunc2;
{ i++, j++, k++} //in bigfunc3;
//blabla...
}
The simplest way is copying the bigfunc 3 times and edit the different lines respectively. Obviously, it is not a good idea.
Now, I choose the template function method in c++, which embraces the different lines into a function, such as:
< template class F >
void bigfunc(F& f){
...
f(i,j,k); //call the function.
...
}
void f1(int i, int j, int k){
i++; //only use parameter i!
}
void f2(int i, int j, int k){
i++; j++; //only use parameter i and j!
}
void f3(int i, int j, int k){
i++; j++; j++;
}
However, we have to unify the prototype of f(int, int, int) to include all input parameters in three different bigfuncs, while in fact, in bigfunc1, only f(int i) is needed indeed. Therefore, this method seems not elegant enough.
I though that if there are some abstract mechanics which can take a sentence block as function parameters or template function parameters. That will be amazing!
Are there some other compiler-time abstract mechanics in any language, which can solve such problem elegantly.
Thanks for any suggestion!
I have a programming problem and I thought it for several days, but still without good solutions.
There are several big, long and similar functions, in which only several lines are different. For example:
void bigfunc(){
//blabla..
int i, j, k;
//only this part is different
{ i++ } //in bigfunc1;
{ i++, j++} //in bigfunc2;
{ i++, j++, k++} //in bigfunc3;
//blabla...
}
The simplest way is copying the bigfunc 3 times and edit the different lines respectively. Obviously, it is not a good idea.
Now, I choose the template function method in c++, which embraces the different lines into a function, such as:
< template class F >
void bigfunc(F& f){
...
f(i,j,k); //call the function.
...
}
void f1(int i, int j, int k){
i++; //only use parameter i!
}
void f2(int i, int j, int k){
i++; j++; //only use parameter i and j!
}
void f3(int i, int j, int k){
i++; j++; j++;
}
However, we have to unify the prototype of f(int, int, int) to include all input parameters in three different bigfuncs, while in fact, in bigfunc1, only f(int i) is needed indeed. Therefore, this method seems not elegant enough.
I though that if there are some abstract mechanics which can take a sentence block as function parameters or template function parameters. That will be amazing!
Are there some other compiler-time abstract mechanics in any language, which can solve such problem elegantly.
Thanks for any suggestion!
No comments:
Post a Comment