[英]Compile-time array constants
我似乎錯過了一些相當基本的東西。 我正在嘗試在編譯時使用const數組成員。
const int list[3] = { 2, 5, 7 };
const int a = list[2]; // this doesn't error?
template<int N1, int N2>
struct tmax {
enum { value = ((N1 > N2) ? N1 : N2) };
};
const int b = tmax<2,4>::value;
const int c = tmax<list[0],list[1]>::value; // error is here
int main()
{
return 0;
}
錯誤:
prog.cpp:10:24: error: 'list' cannot appear in a constant-expression
prog.cpp:10:30: error: an array reference cannot appear in a constant-expression
那么為什么這不起作用呢? 我錯過了什么? 我該怎么辦?
僅僅因為對象是const
並不意味着它是一個編譯時常量表達式。
main.cpp:10:20: error: non-type template argument is not a constant expression
const int c = tmax<list[0],list[1]>::value; // error is here
^~~~~~~
main.cpp:10:20: note: read of non-constexpr variable 'list' is not allowed in a constant expression
main.cpp:1:11: note: declared here
const int list[3] = { 2, 5, 7 };
^
這是constexpr
的原因:
constexpr int list[3] = { 2, 5, 7 };
template<int N1, int N2>
struct tmax {
enum { value = ((N1 > N2) ? N1 : N2) };
};
const int b = tmax<2,4>::value;
const int c = tmax<list[0],list[1]>::value; // works fine now
至於為什么這樣做:
const int a = list[2]; // this doesn't error?
初始化const
變量不需要常量表達式:
int foo(int n) {
const int a = n; // initializing const var with a non-compile time constant
如果表達式包含許多不允許的子表達式中的任何一個,則表達式不是常量表達式。 一類這樣的不允許的子表達式是:
- 除非適用,否則左值到右值的轉換(4.1)
- 一個整數或枚舉類型的glvalue,它引用一個帶有前面初始化的非易失性const對象,用一個常量表達式初始化,或者
- 一個文字類型的glvalue,它指的是用
constexpr
定義的非易失性對象,或者指的是這樣一個對象的子對象,或者- 一個文字類型的glvalue,它引用一個生命周期尚未結束的非易失性臨時對象,用一個常量表達式初始化;
特別是,使用常量初始化程序初始化的枚舉或整數類型的const對象的名稱形成一個常量表達式 (讀取其值是導致左值到右值轉換的原因),const聚合對象的子對象(如如你的例子中的list
,數組)不,但如果聲明constexpr
。
const int list[3] = { 2, 5, 7 };
const int a = list[2];
這是有效的但是a
不構成常量表達式,因為它沒有用常量表達式初始化。
通過改變的申報list
(我們沒有改變的聲明a
),我們可以做a
形式的常量表達式。
constexpr int list[3] = { 2, 5, 7 };
const int a = list[2];
如list[2]
現在是一個常量表達式 , a
現在是一個const
與一個常量表達式所以初始化可積型的對象a
現在可以用作常量表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.