开发者

How to initialize a constant from a non-constant?

How can I initialize a constant to use it as a size parameter for a bitset object, such that it takes its value from anothe non-constant variable?

int x=2;
int y=Some_Function(x);
const 开发者_运维百科int z=y;
bitset<z> b;


You cannot do that because size of arrays or the template parameter tostd::bitset has to be compile-time constant, not runtime constant. The const value must be known at compile-time itself, in order to be used as array-size, or in 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!

The above code and comments are made according to C++98 and C++03.

However, in C++11, y will be compile-time constant, and the code involving y would compile if y is initialized as:

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

and getSize() is defined as:

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

The keyword constexpr has been added to C++11 to define generalize constant expressions.


There's a difference between a constant variable and a compile-time constant. Compare:

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

This variable i is constant with the function scope, but its value is unknown at compile time.

On the other hand, the following two are compile-time constants:

const int a = 12;

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

const int b = f(6);

Both a and b are known at compile time.

Only compile-time constants can be used as array sizes or template parameters! (Templates are essentially code generation machines, so the code has to be generated before the final program can be compiled.)

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!

Note that in C++98/03, b is not actually formally recognized as a compile-time constant. C++11 fixes this by allowing f to be declared constexpr, meaning it's allowed to compute compile-time constant expressions (if all its arguments are themselves constant).


Let's distinguish between compile-time constants and variables with const slapped on them. Yours is the latter kind; only the former kind can serve as array size (before C++0).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜