3

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)?

9
  • 3
    And what is the error C2975? Not all of us know the VC++ compiler errors by heart. Commented Nov 30, 2014 at 18:43
  • Also, try using constexpr instead of const. Commented Nov 30, 2014 at 18:44
  • 1
    msdn.microsoft.com/en-us/library/kyf0z2ka.aspx - basically it says that constant expressions should appear within the angle brackets. Commented Nov 30, 2014 at 18:44
  • 4
    related: Difference between const and constexpr arrays Commented Nov 30, 2014 at 18:46
  • 1
    Is that really what you want to do, BTW? That is, create a std::bitset<N> with 24593 bits? Did you mean to use std::bitset<std::numeric_limits<int>::digits> k(HASH[0]); which also wouldn't suffer from the problems you see? Commented Nov 30, 2014 at 19:44

1 Answer 1

3

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

So it's not possible in VC++... oh well. Thanks for the answer! (and yes I did want 24593 bits)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.