【问题标题】:C++ how can I simplify this if else statement?C++ 如何简化这个 if else 语句?
【发布时间】:2022-08-10 09:15:31
【问题描述】:

我想知道如何简化如下陈述。

我到处都有类似的代码,并想清除它。

if(isActive)
{
    if(columnId == 4)
        g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true);
}
else
{
    if(columnId == 4)
        g.drawText(inactive[row].value, 2, 0, width, height, Justification::centredLeft, true);
}

isActive,你可以想象,是一个bool 值。

  • if(columnId == 4) { g.drawText(isActive ? active[row].value : inactive[row].value, ...); }?
  • auto value_to_pass = isActive? active[row].value : inactive[row].value; g.drawText(value_to_pass, ...);
  • 假设activeinactive 具有相同的类型......if (column[Id == 4) {auto thing = (isActive ? active : inactive)[row].value; g.drawText(thing, 2, 0, width, height, Justification::centred);} 甚至if (columnID == 4) g.drawText((isActive : active : inActive)[row].value, 2, 0, width, height, Justification::centred);。不过,有些人会争论它的可读性。

标签: c++ c++11 c++17 coding-style


【解决方案1】:

乍一看,最明显的是,这段代码只有在columnId == 4 时才会做任何事情。

if(columnId == 4)
{
    if(isActive)
    {
        g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true);
    }
    else
    {
        g.drawText(inactive[row].value, 2, 0, width, height, Justification::centredLeft, true);
    }
}

乍一看,那两条粗大的线条几乎是一样的。

if(columnId == 4)
{
    auto & text = isActive ? active : inactive;
    g.drawText(text[row].value, 2, 0, width, height, Justification::centredLeft, true);
}

另请注意@eeerorika 的有效评论。 ⬇️ 我不能说比他们做得更好。

【讨论】:

  • 请注意,后一种形式要求activeinactive 具有相同的类型。在这种情况下可能是这样,但在总体上考虑这种转换时,这是一个需要理解的重要细节。
【解决方案2】:
if (columnId != 4)
    ; // do nothing
else if (isActive)
    . . .
else
    . . .

【讨论】:

    【解决方案3】:

    通过减少重复文本的数量,可以使用 lambda 来简化原始代码结构。

    auto drawText = [&](auto &table) {
        g.drawText(table[row].value, 2, 0, width, height,
                   Justification::centeredLeft, true);
    };
    
    if(isActive)
    {
        if(columnId == 4) drawText(active);
    }
    else
    {
        if(columnId == 4) drawText(inactive);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2020-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多