Search code examples
c++default-valueoverloading

How to create multiple versions of a method in c++?


I have the following problem. I have programmed the following method. With the flag it is set, which version is used.

#define version2
void calc(double &x
 #ifdef version2
   , double &dot_x
 #endif){
   for(int i=0;i<n;i++){
     double data[]=[... expensive computation ...];
     x=[... something depending on data...];
     #ifdef version2
       dot_x=[... something depending on data ...];
     #endif
   }
}

But now, I need both versions at the same time and I don't want to copy it, because I would have to make changes at the computation of data in both the versions every time. Is there any possibility (like macro etc) to have both versions implemented in one place? And without if-decisions, which cost time?

Thanks a lot for answers,

kildschrote


Solution

  • Just define 2 overloads of your function, one that takes one parameter, one that takes 2:

    void calc(double &x){...}
    
    void calc(double &x, double &dot_x){...}
    

    and factor out the common code. You can then decide (at runtime or at compile time ,via an #ifdef) which one of the overloads you want to call.

    You can even define only one version, with a default second argument (of pointer type),

    void calc(double &x, double *dot_x = nullptr){...}
    

    and if the second argument is not explicitly specified (i.e. is left nullptr), then do the "cheap" computation, if not, do the "expensive" one.

    I would avoid macros as much as possible (unless really necessary), as they can make your code less readable and induce nasty side effects.