Initialization with const array element

Why doesn't the compiler (VC ++) resolve (error C2975)

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

      

and what can I do to overcome this (initialize templates with constant values ​​from an array)?

+3


source to share


1 answer


The local object const

does not qualify as a constant expression, but std::bitset<N>

requires that the N

non-type template parameter be a constant expression. An const

integral object with an initializer qualifies as a constant expression. In all other cases, you will need constexpr

(I don't know if MSVC ++ supports constexpr

). For example:

#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
}

      



All that said, are you sure you really want to have std::bitset<N>

with the number of elements given by the array? If you are really interested in the bits of the value, you would rather use something like this:

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

      

+3


source







All Articles