簡體   English   中英

constexpr和std :: cout處理函數但不處理lambda

[英]constexpr and std::cout working on function but not in lambda

為什么constexpr不能用於std::cout ,但適用於printf

#include <iostream>
constexpr void f() { std::cout << ""; } //error
constexpr void g() { printf(""); } //ok

為什么std::cout與lambdas constexpr

#include <iostream>
int main () {
    auto h = []() constexpr { std::cout << ""; }; //ok
}

從技術上講,它不適用於任何一種。

來自[dcl.constexr]

對於既不是默認也不是模板的constexpr函數或constexpr構造函數,如果不存在參數值,則函數或構造函數的調用可以是核心常量表達式的計算子表達式,或者對於構造函數,可以是常量初始化函數。一些對象([basic.start.static]), 程序格式錯誤,無需診斷

f()g()永遠不是常量表達式( std::cout << xprintf()都不是constexpr函數),因此constexpr聲明constexpr不正確。 但編譯器不需要診斷它(在這種情況下,它可能很容易,但在一般情況下......不是那么多)。 您所看到的是您的編譯器能夠診斷出一個問題而不是另一個問題。

但他們都錯了。

它沒有。 您需要使用它來強制編譯時錯誤。

constexpr int a = f(), 0; // fails
constexpr int b = g(), 0; // fails

從不產生常量表達式的constexpr函數是不正確的; 無需診斷。 這意味着編譯器會盡最大努力檢查是否是這種情況,但是您的程序已經出現錯誤。 好像gcc看不到printf不是常量表達式。 定義中的鏗鏘錯誤

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM