我想在编译时检查一个值,如果它是一个 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))
最佳答案
可能你的问题对我来说有点不清楚。如果你想要一个字符串文字是否应该通过并且指针不应该那么看下面的答案。如果您觉得我误解了您的问题然后发表评论,我将删除此答案或进行相应修改。
您可以使用简单的 C 风格宏来检查给定变量是否为字符串文字,正如我在对以下问题的回答中所解释的那样:
Verify type of string (e.g. literal, array, pointer) passed to a function
#define IS_LITERAL(X) "" X
如果 X
不是字符串文字,编译将失败。
关于c++ - 如果可能,在编译时检查一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34212865/