使用 const 数组元素初始化

Initializing with const array element

本文关键字:初始化 数组元素 const 使用      更新时间:2023-10-16

为什么编译器 (VC++) 不允许 (错误 C2975)

const int HASH[] = {24593, 49157};
bitset<HASH[0]> k;

我能做些什么来克服这个问题(使用数组中的常量值初始化模板)?

本地 const 对象不符合常量表达式的条件,但std::bitset<N>需要非类型模板参数N为常量表达式。具有初始值设定项的const整型对象确实有资格作为常量表达式。在所有其他情况下,您将需要constexpr(我不知道MSVC++是否支持constexpr)。例如:

#include <bitset>
struct S { static int const member = 17; };
int const global_object = 17;
int const global_array[]  = { 17, 19 };
int constexpr global_constexpr_array[] = { 17, 19 };
int main()
{
    int const local = 17;
    int const array[] = { 17, 19 };
    int constexpr constexpr_array[] = { 17, 19 };
    std::bitset<S::member> b_member; // OK
    std::bitset<global_object>             b_global;                 // OK
    std::bitset<global_array[0]>           b_global_array;           // ERROR
    std::bitset<global_constexpr_array[0]> b_global_constexpr_array; // OK
    std::bitset<local>              b_local;           // OK
    std::bitset<array[0]>           b_array;           // ERROR
    std::bitset<constexpr_array[0]> b_constexpr_array; // OK
}

综上所述,您确定是否真的要对数组指定的元素数进行std::bitset<N>?如果你真的对值的位感兴趣,你宁愿使用这样的东西:

std::bitset<std::numeric_limits<unsigned int>::digits> k(HASH[0]);