我以前有代码来提取特定部分
auto& c = m_matrix[name];
....large block of code with using c in the calculation...
现在,我必须为以下语句的m_matrix选项使用if / else或switch大小写:
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;
}
}
您可以使用函数或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...