如果可能的话,在编译时检查一个值

Check a value at compile time if possible

本文关键字:检查 一个 编译 如果      更新时间:2023-10-16

如果一个值是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样式宏来检查给定的变量是否是字符串文字,正如我在回答以下问题时所解释的:
验证传递给函数的字符串类型(例如文字、数组、指针)

#define IS_LITERAL(X) "" X

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