wim*_*aan 6 c++ static-assert constexpr
我知道有一个针对constexpr()运算符的提议,但这尚未在gcc / clang中实现。我也知道使用一些技巧来实现,例如机器代码编辑:
http://saadahmad.ca/detecting-evaluation-context-inside-constexpr-functions/
我想知道是否有某种受限的解决方案:
struct F {
constexpr F(int v) {
if constexpr(constexpr()) {
static_assert(v > 0);
}
else {
assert(v > 0);
}
}
};
// ...
constexpr F f{0}; // should trigger a compile-time error
Run Code Online (Sandbox Code Playgroud)
我知道无法以这种方式使用static_assert,但这只是为了澄清问题。
在您的特定情况下,您可以保留断言 - 当条件错误时,它将阻止编译,因为断言处理程序是非 constexpr:
#include <cassert>
struct F {
constexpr F(int v) {
assert(v >0);
}
};
// ...
constexpr F f1{0}; // doesn't compile in debug
constexpr F f2{1}; // compiles
Run Code Online (Sandbox Code Playgroud)
但是,这不会触发发布中的编译时错误。它可以通过创建自己的断言并添加对某些非 constepxr 函数的调用来解决:
#include <cassert>
// some non-constexpr function
void AssertConditionFailed()
{
}
#define ASSERT_WIH_COMPILE_TIME_CHECK(...) \
assert(__VA_ARGS__); \
if (!(__VA_ARGS__)) \
{ \
AssertConditionFailed(); \
}\
struct F {
constexpr F(int v) {
ASSERT_WIH_COMPILE_TIME_CHECK(v >0);
}
};
// ...
constexpr F f1{0}; // doesn't compile
constexpr F f2{1}; // compiles
Run Code Online (Sandbox Code Playgroud)