【发布时间】:2015-12-10 22:26:01
【问题描述】:
我想在编译时检查一个值,如果它是 constexpr 值,如果是,请在其上运行 constexpr 表单检查函数。
我可以在 c++11/14 中做到这一点吗?
在伪代码中,我想做:
static_if (is_constexpr(x))
static_assert(check(x))
详情:
我正在检查特定格式的字符串。从概念上讲:
template<std::size_t N>
constexpr bool check(const char (&s)[N]){ return true; }
//^ really a recursive call that checks the string
constexpr 检查适用于字符串文字,但不适用于字符串指针:
int main(){
const char* s = "#";
static_assert(check("#"), "Fmt");; //OK
//This fails; expectation was it suceeds and the check doesn't run
static_assert(!is_constexpr(s) || check(s), "Fmt");
}
is_constexpr 是:
#include <type_traits>
template<typename T>
constexpr typename std::remove_reference<T>::type makeprval(T && t) {
return t;
}
#define is_constexpr(e) noexcept(makeprval(e))
【问题讨论】:
-
“重复”是指生成一个包含此结果的
bool。如果您想中止编译,那么可能有不同的解决方案。 -
static_assert(x || !x, "");怎么样。如果x不是常量,则编译失败,如果它是常量,则什么也不会发生。 -
@M.M 我只想在值为 constexpr 并且我的 constexpr 检查失败时中止编译。
-
好的,我重新打开了这个问题,因为这与之前的副本有很大不同
-
@PSkocik:我理解你想要做什么,虽然我不知道怎么做,或者是否有可能。我认为您的问题比链接的问题要复杂得多,因为即使
is_constexpr()工作,您可能仍然会遇到!is_constexpr(s) || check(s)的未评估部分不是常量表达式的问题。根据我的理解,您希望实现static_if (is_constexpr(s)) static_assert(check(s))