2017-07-28 62 views
1

我試圖比較一個constexpr-if語句中的函數參數。在constexpr-if條件下比較constexpr函數參數會導致錯誤

下面是一個簡單的例子:

constexpr bool test_int(const int i) { 
    if constexpr(i == 5) { return true; } 
else { return false; } 
} 

然而,當我用下面的標誌編譯這個海灣合作委員會7: g++-7 -std=c++1z test.cpp -o test 我收到以下錯誤信息:

test.cpp: In function 'constexpr bool test_int(int)': 
test.cpp:3:21: error: 'i' is not a constant expression 
if constexpr(i == 5) { return true; } 

然而,如果我將test_int替換爲不同的功能:

constexpr bool test_int_no_if(const int i) { return (i == 5); } 

然後將下面的代碼編譯沒有任何錯誤:

int main() { 
    constexpr int i = 5; 
    static_assert(test_int_no_if(i)); 
    return 0; 
} 

我不明白爲什麼constexpr,如果版本編譯失敗,特別是因爲static_assert工作得很好。

任何意見,將不勝感激。

謝謝!

+2

爲什麼constexpr(i == 5)而不只是我== 5? – deW1

+0

任何爲什麼這麼複雜?爲什麼不返回我== 5? – deW1

回答

5

constexpr if

在constexpr if語句,的條件的值必須是 上下文轉換bool類型常量表達式

然後,從constant expression

定義可以在編譯時計算的表達式。

顯然,i == 5不是一個常量表達式,因爲i是在運行時計算一個函數參數。這就是編譯器抱怨的原因。

當您使用功能:

constexpr bool test_int_no_if(const int i) { return (i == 5); } 

那麼可以在編譯時間取決於它是否是參數在編譯時知道或不進行評估。

如果i的定義如下:

constexpr int i = 5; 

那麼i值在編譯時已知和test_int_no_if可能在編譯過使它可以調用它裏面static_assert進行評估。

另請注意,標記函數參數const不會使其成爲編譯時間常量。這只是意味着你不能改變函數內部的參數。

1

一個constexpr函數可以用非constexpr參數調用,在這種情況下,它的行爲就像一個普通函數,所以代碼仍然必須編譯,就好像它不是constexpr。

簡而言之,test_int_no_if中沒有任何內容取決於我是否是constexpr,而在test_int()中則有。 (「constexpr if」僅適用於編譯時表達式。)

相關問題