」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 為什麼編譯器中的「static_assert」與非型別模板參數的行為不同?

為什麼編譯器中的「static_assert」與非型別模板參數的行為不同?

發佈於2024-11-09
瀏覽:262

Why Does `static_assert` Behave Differently with Non-Type Template Parameters Across Compilers?

編譯器中非型別模板參數的 static_assert 行為不一致

在 C 中,static_assert 在編譯時可驗證條件。然而,最近的觀察發現,當 static_assert 與不同編譯器中的非類型模板參數結合使用時,其行為存在差異。

具體來說,以下程式碼片段:

template 
struct Hitchhiker {
  static_assert(sizeof(answer) != sizeof(answer), "Invalid answer");
};

template 
struct Hitchhiker {};

嘗試使用 static_assert 停用通用範本實例化時,在 Clang 和 GCC 上的行為有所不同。即使模板未實例化,Clang 也會觸發斷言錯誤,而 GCC 僅在使用 42 以外的參數值實例化時才會引發錯誤。

要了解差異,讓我們探索C 標準的相關部分( [temp.res]/8):

If no valid specialization can be generated for a template, and that template is not instantiated, the template is ill-formed, no diagnostic required.

根據此規則,主範本Hitchhiker 格式錯誤,因為無法產生有效的專業化。因此,不需要發出診斷。然而,儘管缺乏要求,Clang 還是選擇提供診斷。

如果意圖將實例化限制為僅 42 個,建議的方法是省略通用模板定義,如下所示:

template 
struct Hitchhiker {};
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3