"Cannot appear in a constant expression", I need this to be a variable, why won't it let me?

You can't. Template parameters like that need to be known at compile time since the compiler will need to generate different code based on the values passed.

In this case you probably want to iterate through your string instead and build up the value yourself, e.g.

unsigned long result = 0;
for(int i = 0; i < binary_value.length(); ++i)
{
    result <<= 1;
    if (binary_value[i] != '0') result |= 1;
}

which also assumes that your result is shorter than a long, though, and won't accommodate a 256-bit value - but neither will your sample code. You'll need a big-number type for that.


std::bitset's size can only be a compile-time known constant (constant expression) because it is an integral template parameter. Constant expressions include integral literals and/or constant integer variables initialized with constant expressions.

e.g.

std::bitset<4> q; //OK, 4 is a constant expression
const int x = 4;
std::bitset<x> qq; //OK, x is a constant expression, because it is const and is initialized with constant expression 4;
int y = 3;
const int z = y;
std::bitset<z> qqq; //Error, z isn't a constant expression, because even though it is const it is initialized with a non-constant expression

Use std::vector<bool> or boost::dynamic_bitset(link here) instead for dynamic (not known compile-time) size.


You don't - std::bitset is a template, its size must be specified at compile-time.

You need to make convert_binary_to_hex a template on its own. If the size is only known at runtime, you have to find another solution.

template<size_t number_of_bits>
string convert_binary_to_hex(string binary_value)
{
   bitset<number_of_bits> set(binary_value);   
   ostringstream result;
   result << hex << set.to_ulong() << endl;
   return result.str();
}

Tags:

C++

Bitset