0

I have a huge chunk of code that works on say two version of some param , let say ver1 and ver2.

Version is a run time field and i intend to keep it as, so that i don't have to build the code with different flags and same lib files can be used for both versions.

Now, there are different fields that are applicable for ver1 and some for ver2.

So in the code at multiple places i have to do

if(ver1) {
    // set fields specific to ver1
}
else {
    // set fields specific to ver2
}

I don't like the idea of putting so may if statements in the code, as the code tends to look ugly.

Any alternatives this ?

I was thinking some generic inline / macro definition where a field is set only if flag passed is true ?

Also, on the optimization side , should not be expensive than if else

@edit -- some details of internal organization of code

Can't post the details of code. But one important matter of fact is that its a huge legacy code which needs upgrade with backward compatibility.

The version param is passed to each class to decide what field is to be set and which to ignore.

4

3 回答 3

3

一种常用的解决方案是有两个代表版本 1 和版本 2 的类,用一个通用基类定义与虚函数的接口。所以,你只会得到一个 if/else,然后虚函数表会负责选择正确的函数。

如果这不是一个合理的解决方案,那么 if-else 是最清晰的方法,我会说。

于 2013-10-09T07:48:10.527 回答
0

如果它只是化妆品,那么:

void blabla0(bool ver1)
{
 if(ver1)
 {
  blabla1();
  return;
 }
 blabla2(); // save one else and two brackets, but get a return :-(
}

如果您在编译时总是知道参数,那么我会使用模板

template<bool ver> blabla0()
{
 if(ver1)
 {
  blabla1();
  return;
 }
 blabla2();
}

这既高效(编译器将构建该函数的两个专用版本)又清晰。

我忘记了另一个:

void blabla0(bool ver1)
{
 ver1 ? blabla1(): blabla2();
}

或者按照 Mats Petersson 的建议,使用具有两个专用于每个版本的派生类的基本虚拟类。

于 2013-10-09T08:04:36.360 回答
0

您可以使用函数轻松地做到这一点。函数的基本目的是减少代码冗余。

#define VERSION1 25
#define VERSION2 55

void checkVersion(int vers)
    {
       switch(vers)
       {
         case VERSION1:
              code_Depending_On_Version1();
              break;


         case VERSION2:
              code_Depending_On_Version2();
              break;
        }
    }
于 2013-10-09T07:49:07.427 回答