如何简化此typedef不同的switch语句?

时间:2012-07-14 22:06:25

标签: c++ coding-style switch-statement

我正在对char执行switch语句,而且'A''a'之间的唯一区别通常是特定结构中的某些静态常量和随机数字常量。这是一个例子:

switch(someChar)
{
case 'A':
{
    typedef structWithConstants<caseA, UPCASE> constantsT;
    someStruct s;
    s.bla = bla;
    s.foo = getfoo7(rat+constantsT::rat);
    s.other = getOther10(other + constantsT::other);

    someFunctionBar(&s);
}
break;
case 'a':
{
    typedef structWithConstants<caseA, LOWCASE> constantsT;
    someStruct s;
    s.bla = bla;
    s.foo = getfoo3(rat+constantsT::rat);
    s.other = getOther10(other + constantsT::other);

    someFunctionBar(&s);
}
break;
}

所以在上面,从字面上看,代码方面的唯一区别是使用的常量T和7切换到3 ......是否有一种方法可以简化重复代码?也许会破坏两种情况之间的一些常见行为?

4 个答案:

答案 0 :(得分:4)

可以模拟一个函数,为那些'foo'-s声明一个类型,然后将套管模板参数传递给某个调用函数

typedef int getfootype(char c);

template<getfootype f,char CASING>
void  handle(char c)
{
        typedef structWithConstants<caseA, CASING> constantsT;
        someStruct s;
        s.bla = bla;
        s.foo = f(rat+constantsT::rat);
        s.other = getOther10(other + constantsT::other);

        someFunctionBar(&s);
}

switch(someChar)
{
    case 'A':
          handle<getfoo7,UPCASE>(someChar);
       break;
    case 'a':
          handle<getfoo3,LOWCASE>(someChar);
       break;
}

答案 1 :(得分:1)

类似的东西:

switch(someChar)
{
case 'A':
case 'a':
{
    typedef structWithConstants<caseA, UPCASE> constantsT_UP;
    typedef structWithConstants<caseA, LOWCASE> constantsT_LO;
    someStruct s;
    s.bla = bla;
    if (someChar == 'a')
      s.foo = getfoo3(rat+constantsT_LO::rat);
     else
    s.foo = getfoo7(rat+constantsT_UP::rat);
    s.other = getOther10(other + (someChar == 'a') ? constantsT_LO::other : constantsT_UP::other);

    someFunctionBar(&s);
}
break;
}

但看起来很复杂......

答案 2 :(得分:1)

将重复部分放在switch

之外
someStruct s;
s.bla = bla;

switch(someChar)
{
case 'A':
    typedef structWithConstants<caseA, UPCASE> constantsT;
    s.foo = getfoo7(rat+constantsT::rat);
break;
case 'a':
    typedef structWithConstants<caseA, LOWCASE> constantsT;    
    s.foo = getfoo3(rat+constantsT::rat);
break;
}

s.other = getOther10(other + constantsT::other);
someFunctionBar(&s);

答案 3 :(得分:0)

    switch(someChar)
    {
    case 'A': case 'a' :
    {
        typedef structWithConstants<caseA, UPCASE> constantsT;
        someStruct s;
        s.bla = bla;
        if(someChar == 'A')
            s.foo = getfoo7(rat+constantsT::rat);
        else if(someChar == 'a')
            s.other = getOther10(other + constantsT::other);

        someFunctionBar(&s);

        s.foo = getfoo3(rat+constantsT::rat);
        break;
    }