简体   繁体   English

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

[英]Check a value at compile time if possible

I'd like to check a value at compile time, if it's a constexpr value and do run a constexpr form-checking function on it if it is. 我想在编译时检查一个值(如果它是constexpr值),如果是,请对其运行constexpr表单检查功能。

Can I do this in c++11/14? 我可以在c ++ 11/14中执行此操作吗?

In pseudo code, I'd like to do: 用伪代码,我想做:

static_if (is_constexpr(x)) 
      static_assert(check(x))

Details: 细节:

I'm checking a string for a particular format. 我正在检查一种特定格式的字符串。 It's conceptually: 从概念上讲:

template<std::size_t N>
constexpr bool check(const char (&s)[N]){ return true; }
//^ really a recursive call that checks the string

The constexpr check works with a string literal, but not with a string pointer: 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");

}

The is_constexpr is: 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))

May be your question is bit unclearer to me. 可能您的问题对我来说还不清楚。 If you want whether a string literal should pass and pointer should not then look at below answer. 如果您想确定是否应该传递字符串文字并且不应该使用指针,那么请看下面的答案。 Should you feel that, I have misunderstood your question then comment it, I shall delete this answer or modify accordingly. 如果您觉得我误会了您的问题,然后发表评论,我将删除此答案或进行相应的修改。

You can use simple C-style macro to check if given variable is a string literal, as I have explained in my answer to below question: 您可以使用简单的C样式宏来检查给定变量是否为字符串文字,正如我在对以下问题的回答中所解释的:
Verify type of string (eg literal, array, pointer) passed to a function 验证传递给函数的字符串类型(例如,文字,数组,指针)

#define IS_LITERAL(X) "" X

The compilation will fail if the X is not a string literal. 如果X不是字符串文字,则编译将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM