【发布时间】:2020-04-23 22:00:12
【问题描述】:
我有一个 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,但没有找到。
有什么技巧可以让表达式中的编译时错误可以被常量评估?
【问题讨论】:
-
static_assert在编译时进行评估。因此,它检查的表达式必须是constexpr,而不仅仅是const。这就是问题所在:你的函数compile_time_error函数的编译总是会失败。 -
只需使用
runtime_error()。如果在编译时求值会报错。
标签: c++ gcc assertion c++20 constant-expression