任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?
Can an arbitrary-sized constexpr array be used as cases in a switch statement?
可以在switch语句中使用可变大小的constexpr数组,以便每个arr[i]都是一个案例?还是if语句是唯一的解决方案。
constexpr int arr[] = {35, 2, 234, 42, ..., N}; // <------ Random ints
constexpr int size = sizeof(arr)/sizeof(arr[0]); // <----arbitrary number of elements in array
// want to achieve something like this
switch (var) {
case inArray(var): /* Checks if the var is in the array. Cannot be done at
compile time due to runtime var. Thats why I was looking for a workaround where the switch accepted a range of array values
then expanded it automatically upon compilation */
// other cases
}
抱歉,只是为了澄清一下,我正在寻找类似于"案例范围"的功能,该功能由一些编译器提供,他们为您创建案例陈述。我知道编译器会在编译时知道大小。在我的应用程序中,此大小将经常更改。我已经编辑了上面的代码,以更好地反映我要追求的逻辑。
标准设置为最新的 VS2019 接受以下代码:
constexpr int arr[]{ 5, 6, 7, 35 };
constexpr int sizeArr{ sizeof(arr) / sizeof(arr[0]) };
void foo(int v)
{
switch(v) {
case arr[0]
: break;
case arr[1]
: break;
case arr[2]
: break;
case arr[sizeArr - 1]:
break;
}
}
是的,但必须正确
计算数组的大小 例如 var 由 99 组成
constexpr int arr[] = {35, 2, 234, 42, 99, 67}; // <------ Random ints
constexpr int size = sizeof(arr) / sizeof(int) ; // <----arbitrary number of elements in array
int var = 99;
// want to achieve something like this
switch (var) {
case arr[0]:{
cout<< "0"<<"n";
break;
}
case arr[1]:{
cout<< "1"<<"n";
break;
}
case arr[4]:{
cout<< "4"<<"n";
break;
}
case arr[size-1]:
cout<< size-1 <<"n";
break;
}
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 如何将 if else 语句重写为 switch 语句
- Switch 语句(字符串)一直选择默认值,除非其为零
- C++ switch 语句:对案例进行分组,并针对每个案例给出特定的说明
- 任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?
- 默认标签显然在 switch 语句中不起作用
- C++如何在 switch 语句中放置两个参数
- 如何在 c++ 中从 switch 语句返回不同类型的变量
- 在编译时自动生成用于稀疏数组索引的switch语句
- C++ Switch 语句中的数学运算
- 变量不能在 lambda 中隐式捕获,并且没有使用 switch 语句指定捕获默认值
- 在任何案例之前,在 switch 语句中的使用声明是否合法?
- 使用 switch 语句将不同的函数作为类属性分配 C++
- 为什么我的 switch 语句没有响应一半的情况?
- 如何从映射中获取值并在 C++ 的 switch 语句中使用它
- switch 语句导致发送两条消息
- C++ Switch 语句在中断后执行
- switch语句,两种类似情况不同
- switch 语句和对象隐式 int 转换
- switch 语句结束和下一条语句之间的时间是否具有确定性(与路径无关)