首页 > 解决方案 > 可以将任意大小的 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

}

抱歉,只是为了澄清一下,我正在寻找一些编译器提供的类似于“案例范围”的功能,它们会在其中为您创建案例语句。我知道编译器会在编译时知道大小。在我的应用程序中,这个大小会经常变化。我已经编辑了上面的代码,以更好地反映我想要的逻辑。

标签: c++switch-statementconstexpr

解决方案


标准设置为 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;
    }
}

推荐阅读