GILGAMESH
GILGAMESH

Reputation: 1856

Initializing with const array element

Why does the compiler (VC++) not allow (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 array)?

Upvotes: 3

Views: 169

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

A local const object doesn't qualify as a constant expression but std::bitset<N> requires the non-type template parameter N to be a constant expression. A const integral object with an initializer does qualify as a constant expression. In all other cases you'll 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 a std::bitset<N> with the number of elements specified by the array? If you are actually interested in the bits of the value, you'd rather use something like this:

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

Upvotes: 3

Related Questions