简体   繁体   English

为什么不能使用 constexpr if (expression) ,甚至可以在编译时计算表达式

[英]why can't use constexpr if (expression) , even the expression can be evaluated at compile time

//code1
class Test {
public:
  constexpr Test(const char *p) : p_(p) {}
  constexpr int foo() const 
  {
    if(p_[0] != 'a')
      return 1;
    else
      return 2;
  }
  const char *p_;
};

int arr[Test("bbb").foo()];  //this works

why the following code not work?为什么下面的代码不起作用?

  //code2
  constexpr int foo() const 
  {
    constexpr if (p_[0] != 'a') //add constexpr
      return 1;
    else
      return 2;
  }

Got an error:出现错误:

error: expected unqualified-id before 'if'错误:'if' 之前的预期不合格 ID

To my understanding, since " p_[0] != 'a' " can be evaluated at compile time(as shown in code1), so constexpr if (p_[0] != 'a') should be a valid statement which can be evaluate during compiling.据我了解,由于“ p_[0] != 'a' ”可以在编译时进行评估(如代码1所示),所以constexpr if (p_[0] != 'a')应该是一个有效的语句,它可以在编译过程中进行评估。

To my understanding, since " p_[0] != 'a' " can be evaluated at compile time(as shown in code1), so constexpr if (p_[0] != 'a') should be a valid statement which can be evaluate during compiling.据我了解,由于“ p_[0] != 'a' ”可以在编译时进行评估(如代码1所示),所以constexpr if (p_[0] != 'a')应该是一个有效的语句,它可以在编译过程中进行评估。

p_[0] != 'a' can be evaluated compile-time but can also be evaluated run-time. p_[0] != 'a'可以在编译时求值,但也可以在运行时求值。

The problem is that a if constexpr test must be evaluated compile-time.问题是必须在编译时评估if constexpr测试。 And this is impossible when foo() is executed run-time or when the corresponding Test object is initialized run-time.foo()在运行时执行或相应的Test对象在运行时初始化时,这是不可能的。

So the error.所以错误。

Or better: the error if you write correctly或者更好:错误如果你写得正确

if constexpr (p_[0] != 'a')

In your case the order between if and constexpr is also wrong.在您的情况下, ifconstexpr之间的顺序也是错误的。

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

相关问题 为什么for循环不是编译时表达式,扩展constexpr允许constexpr函数中的for循环 - why for-loop isn't a compile time expression and extended constexpr allows for-loop in a constexpr function C ++ constexpr - 可以在编译时评估值吗? - C++ constexpr - Value can be evaluated at compile time? 编译器无法执行 constexpr 表达式 - Compiler can't execute constexpr expression 如何判断表达式是在编译时还是在运行时进行计算? - How to tell if expression is evaluated at compile time or runtime? Constexpr 构造函数不在编译时求值 - Constexpr constructor is not evaluated at compile time 强制在编译时评估constexpr - Force constexpr to be evaluated at compile time 什么时候在编译时评估 constexpr? - When is a constexpr evaluated at compile time? 为什么在运行时而不是在编译时使用 constexpr 初始化变量 - Why is initialization of variable with constexpr evaluated at runtime instead of at compile time 为什么带有指针子对象的文字 class 类型的 constexpr 表达式不能是非类型模板参数 - why a constexpr expression of literal class type with a pointer subobject can't be a non-type template argument 我可以在编译时使用 constexpr function 在数组上运行算法吗? - Can I use a constexpr function to run an algorithm on an array at compile time?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM