如何初始化常量以将其用作bitset对象的大小参数,以便从非常量变量获取其值?
int x=2;
int y=Some_Function(x);
const int z=y;
bitset<z> b;
Run Code Online (Sandbox Code Playgroud)
你不能这样做,因为数组的大小或模板参数std::bitset必须是编译时常量,而不是运行时常量.该const值必须在编译时自身知道,以便用作数组大小或在std::bitset.
int x = getSize();
const int y = x; //ok - runtime const. y cannot be changed; x can be changed!
int a[y]; //error in ISO C++ - y is not known at compile time!
std::bitset<y> b; //error in ISO C++ - y is not known at compile time!
const int z = 10; //ok - compile-time const. z cannot be changed!
int c[z]; //ok - z is known at compile time!
std::bitset<z> d; //ok - z is known at compile time!
Run Code Online (Sandbox Code Playgroud)
上面的代码和注释是根据C++ 98和C++ 03制作的.
但是,在C++ 11中,y将是编译时常量,如果初始化为,则涉及的代码y将编译为: y
const int y = getSize(); //i.e not using `x` to initialize it.
Run Code Online (Sandbox Code Playgroud)
并 getSize()定义为:
constexpr int getSize() { /*return some compile-time constant*/ }
Run Code Online (Sandbox Code Playgroud)
该关键字constexpr已添加到C++ 11中以定义通用常量表达式.