C++"不能出现在常量表达式中",我需要这个变量,为什么它不会让我?

Nul*_*uli 6 c++

string convert_binary_to_hex(string binary_value, int number_of_bits)
{
    bitset<number_of_bits> set(binary_value);   
    ostringstream result;
    result << hex << set.to_ulong() << endl;
    return result.str();
}
Run Code Online (Sandbox Code Playgroud)

所以,在上面的方法中,我将二进制字符串转换为十六进制字符串.由于十六进制值是4位,number_of_bits变量需要是4的倍数...因为我正在编写的应用程序中binary_value的范围可以是4位到256位.

那么......我如何获得可变大小的bitset?

我的进口:

#include <stdio.h>
#include <iostream>
#include <string>
#include <bitset>
#include <sstream>
Run Code Online (Sandbox Code Playgroud)

Rup*_*Rup 7

你不能.这样的模板参数需要在编译时知道,因为编译器需要根据传递的值生成不同的代码.

在这种情况下,您可能希望迭代字符串并自行构建值,例如

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

但是,假设您的结果比较长,并且不会容纳256位值 - 但您的示例代码也不会.你需要一个大数字类型.


Arm*_*yan 5

std::bitset的大小只能是编译时已知的常量(常量表达式),因为它是一个完整的模板参数.常量表达式包括用常量表达式初始化的整数文字和/或常量整数变量.

例如

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
Run Code Online (Sandbox Code Playgroud)

使用std::vector<bool>boost::dynamic_bitset(链接此处)代替动态(未知编译时)大小.