簡體   English   中英

如果可能,在編譯時檢查一個值

[英]Check a value at compile time if possible

我想在編譯時檢查一個值(如果它是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不是字符串文字,則編譯將失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM