2

我正在对 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 切换到三......有没有办法简化上面的重复代码?也许会破坏这两种情况之间的一些共同行为?

4

4 回答 4

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;
}
于 2012-07-14T22:35:28.247 回答
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;
}

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

于 2012-07-14T22:12:00.957 回答
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);
于 2012-07-14T22:15:25.607 回答
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;
    }
于 2012-07-14T22:12:56.247 回答