c++ - 可以将任意大小的 constexpr 数组用作 switch 语句中的 case 吗?
问题描述
可以在 switch 语句中使用可变大小的 constexpr 数组,以便每个 arr[i] 都是一个 case 吗?或者 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
}
抱歉,只是为了澄清一下,我正在寻找一些编译器提供的类似于“案例范围”的功能,它们会在其中为您创建案例语句。我知道编译器会在编译时知道大小。在我的应用程序中,这个大小会经常变化。我已经编辑了上面的代码,以更好地反映我想要的逻辑。
解决方案
标准设置为 latest 的最新 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;
}
}
推荐阅读
- azure - 如何对遥测传送到 Application Insights 存储桶进行故障排除?
- r - 如何使用函数从数据帧的每一行生成多行,然后将它们重新加入/合并?
- javascript - Javascript 返回字符串中的特定整数,同时删除其余整数
- php - 如何替换 JSON 数组中键“program_id”的值?
- reactjs - 如何在不同组件之间传递数据?
- google-cloud-platform - 如何使用 Google Cloud Functions 和 Firestore 作为任务管理器
- html - 如何在小部件的单行中对齐具有长标题的产品?我可以添加 textoverflow 属性来解决它吗?
- python - 类的惰性计算
- .net - 命名空间“NamespaceName”中的“类型”不明确 - 在调试模式下构建,在发布模式下失败
- linux - bash - 每个目录的文件数和最后的总数