c++ - 如何以其他方式或转换案例格式编码auto&?

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

我以前有一段代码来提取某些部分

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

现在我必须使用if / else或switch大小写m_matrix选项,例如以下语句:
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;。切换/案例之前以及以下内容:
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...
   }
}

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

最佳答案

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

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

关于c++ - 如何以其他方式或转换案例格式编码auto&?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59331879/

相关文章:

java - Java中如何判断用户输入的字符串是否为某个字母?

java - 当 if 条件为常量时,为什么无法检测到无法访问的代码?

c++ - 模仿 "if constexpr"行为,不可能?

c++ - 没有 PROGMEM 的 Adafruit gfx 库 drawBitmap

c++ - 使用 STL 搜索原始字节并将其替换为文件,最好/正确的方法是什么

c++ - 在C++11中如何表达普通的存储(导出)和加载(导入)屏障(fence)?

C++ decltype 无法推导类型

c++ - Negamax C++实现产生错误结果

c++ - 为什么 const 成员可以初始化两次?

c++ - 打开 Excel 窗口时,IsWindowVisible() 能否返回 false