Search code examples
c++flags

Switch betweeen method versions


I need to rewrite some c++ classes and I would like to be able to switch between the new code and the old code (reliable and fast). What would be good options to do so? In general I need some kind of switch that decides what to do, like:

int foo::bar()
{
   if (yesUseNew == true)
  {
    return 1 + 1;
  }
  else
  {
    return 1 + 2;
  }
}

HOW and where could i set yesUseNew? It should be useable in Debug-Build and in Release and it should be applied directly. So reading some xml-Config would be to late.

The attempt, with two code-versions directly in the methods, is only an example. At this point I am not sure on which abstraction level I will do this. The primary question is actually HOW I can distinguish between the versions (fast).

Thanks!


Solution

  • Well, I see the following alternatives :

    1. At compile time with #define

    e.g:

    #define V1  //Comment this line if you want V2. You can also define it on the command line of your compiler
    
    void myfunction() {
    #ifdef V1
    //V1 Implementation
    #else
    //V2 Impl
    #endif
    
    1. At runtime with env variables for example

    This means you can switch without recompiling.

    if (std::getenv("V1"))
        //V1 Code
    else
        //V2 Code
    
    1. Add a configuration option to your app, either in the command line or the config file if it has one. If the dual behaviour will last this is the way to go