【问题标题】:How to code the auto& in a if else or switch case format?如何以 if else 或 switch case 格式对 auto& 进行编码?
【发布时间】:2019-12-14 02:37:06
【问题描述】:

我曾经有一段代码可以提取某些部分

auto& c = m_matrix[name];
....large block of code with using c in the calculation...

现在我必须为 m_matrix 选项使用 if/else 或 switch case,如下语句:

switch input{
  case 1:
     auto& c = A[name];
  case 2:
     auto& c = B[name];
}
....large block of code with using c in the calculation...

A 和 B 具有相同类型的元素。但是,这是错误的,因为它表明 c 的定义是重复的。同时我不能声明auto&c;在 switch/case 之前以及如下所示:

auto& c;
switch input {
   case 1:
      c = A[name];
   case 2:
      c = B[name];
}

....large block of code with using c in the calculation...

有没有办法解决这个问题?

更新:CinCout - 恢复莫妮卡请提供解决方案

switch input {
   case 1:{
      auto& c = A[name];
      ....large block of code with using c in the calculation...
   }
   case 2:{
      auto& c = B[name];
      ....large block of code with using c in the calculation...
   }
}

有没有办法避免每种情况下的重复代码?谢谢

【问题讨论】:

  • 矩阵表达式或它们的元素是否都具有相同的类型,或者类型是否不同?
  • 另外,您的问题将通过语言标签获得更多关注。这看起来像 C++,除了“结束”?
  • 感谢您的回复。元素都具有相同的类型。
  • “我也不能在 switch/case 之前声明 auto&c;。” 绝对不能作为 参考,但你当然可以它作为变量或指针。
  • 你需要说明A和B是如何声明的。

标签: c++ c++11 if-statement switch-statement auto


【解决方案1】:

只需给每个case 一个自己的范围,有效地给每个c 一个本地范围:

switch input
{
  case 1:
  {
     auto& c = A[name];
     …
     break;
  }
  case 2:
  {
     auto& c = B[name];
     …
     break;
  }
}

【讨论】:

  • 感谢您的回复。我在 switch 之外也有一个相对较大的代码块可以使用。我是否需要在每个范围内重复相同的代码(...)。还有其他更有效的方法吗?如果我将带有 c 的代码放在开关盒之外,代码似乎仍然是错误的。
  • auto& c = A[名称];或自动& c = B[名称];不一样。但其余代码......使用 c 将是相同的。
  • 我不确定你的意思。请编辑您的问题以发布相关代码
  • 好吧,把它放在问题里。
  • @hibernateisland 查看我的评论
【解决方案2】:

您可以使用函数或 lambda:

auto get_c = [&] -> decltype(A[name])& {
    switch (input) {
    case 1:
        return A[name];
    case 2:
        return B[name];
    }
    return A[name];    // default case
};
auto& c = getC();
....large block of code with using c in the calculation...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多