[英]How to get a compile time error in constant evaluated expression?
我有一個Assert
函數,用於評估斷言:
如果先決條件在運行時失敗,此函數將輸出錯誤消息並終止程序。
如果先決條件在常量表達式中失敗,則會導致編譯時錯誤。
我希望當斷言在常量評估表達式中失敗時,此函數也會生成編譯時錯誤:
const int a = (Assert(false),0); //generate a runtime error
//=> I would like it generates a compile time error
我想過使用std::is_constant_evaluated
: compiler-explorer
#include <type_traits>
using namespace std;
void runtime_error();
constexpr void compile_time_error(){} //should generates a compile time error
constexpr void Assert(bool value){
if (value) return;
if (is_constant_evaluated())
compile_time_error();
else
runtime_error();
}
void func(){
const int a = (Assert(false),0);
}
我只使用 GCC,我一直在尋找一個會導致編譯時錯誤的內置函數,這將是一個 constexpr 但沒有找到。
是否有任何技巧可以在表達式中獲得可以被常量評估的編譯時錯誤?
您可以調用未在任何地方定義的函數以導致編譯時錯誤。 或者,由於您無論如何都在使用 gcc,因此您可以從常量部分內部調用屬性錯誤函數,從而在編譯此單元期間導致編譯時錯誤。 要使其工作,您必須在啟用優化的情況下進行編譯。
我看到使用std::is_constant_expression
它在 gcc 9.2 中不起作用,但我設法將它與__builtin_constant_p
。
#include <type_traits>
constexpr void Assert(bool value) {
if (__builtin_constant_p(value)) {
if (!value) {
extern __attribute__(( __error__ ( "error" ) ))
void compile_time_error(void);
compile_time_error();
}
} else {
if (!value) {
void runtime_error();
runtime_error();
}
}
}
void func(int b) {
const int a = (Assert(false), 0);
Assert(b == 0);
}
我曾經用 CI 編寫了一個名為curb的庫,它可以做這樣的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.