【问题标题】:Check a value at compile time if possible如果可能,在编译时检查一个值
【发布时间】: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))

标签: c++ c++11 c++14


【解决方案1】:

可能你的问题对我来说有点不清楚。如果您想是否应该通过字符串文字并且不应该通过指针,请查看以下答案。如果您觉得我误解了您的问题然后发表评论,我将删除此答案或进行相应修改。

您可以使用简单的 C 风格宏来检查给定变量是否为字符串文字,正如我在对以下问题的回答中所解释的那样:
Verify type of string (e.g. literal, array, pointer) passed to a function

#define IS_LITERAL(X) "" X

如果X 不是字符串文字,则编译将失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2012-09-09
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    相关资源
    最近更新 更多