[英]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);
a
和b
在編譯時都是已知的。
只有編譯時常量可以用作數組大小或模板參數,(模板本質上是代碼生成機器。因此必須在編譯最終程序之前生成代碼。)
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.