繁体   English   中英

如何从非常数初始化常量?

[英]How to initialize a constant from a non-constant?

如何初始化常量以将其用作位集 object 的大小参数,以便它从另一个非常量变量中获取其值?

int x=2;
int y=Some_Function(x);
const int z=y;
bitset<z> b;

您不能这样做,因为 arrays 的大小或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!

以上代码和注释是根据C++98和C++03做的。

但是,在y中, y将是编译时常量,如果y初始化为:

 const int y = getSize(); //i.e not using `x` to initialize it.

getSize()定义为:

 constexpr int getSize() { /*return some compile-time constant*/ }

关键字constexpr已添加到 C++11 以定义泛化常量表达式

常量变量和编译时常量是有区别的。 相比:

int main(int argc, char* argv[])
{
  const int i = argc; // constant
}

这个变量i在 function scope 中是常数,但它的值在编译时是未知的。

另一方面,以下两个是编译时常量:

const int a = 12;

int f(int n) { return 2 * n; }  // see below

const int b = f(6);

ab在编译时都是已知的。

只有编译时常量可以用作数组大小或模板参数,(模板本质上是代码生成机器。因此必须在编译最终程序之前生成代码。)

std::bitset<a> B1; // OK, same as std::bitset<12>
std::bitset<b> B2; // OK in C++11, not allowed in C++98/03

// but, in main() above:
std::bitset<i> B3; // Cannot do, we don't know i at compile-time!

请注意,在 C++98/03 中, b实际上并未被正式识别为编译时常量。 C++11 通过允许将f声明为constexpr来解决此问题,这意味着它可以计算编译时常量表达式(如果它的所有 arguments 本身都是常量)。

让我们区分编译时常量和带有const的变量。 你的是后一种; 只有前一种可以用作数组大小(在 C++0 之前)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM