我已经理解了
const
和constexpr
之间的差异及其应用程序,但我无法得到以下错误:
// .hpp file
class MyClass {
public:
constexpr double Square(double toBeSquared);
static constexpr double Cube(double x);
double ProcessRoutine();
};
// .cpp file
constexpr double alternative_square_routine(double x)
{
return x * x;
}
double MyClass::Square(double toBeSquared)
{
return x * x;
}
double MyClass::Cube(double x)
{
return x * x * x;
}
double MyClass::ProcessRoutine()
{
// C2131: expression did not evaluate to a constant
constexpr double square_const = Square(10.0);
// This is fine:
const double another_square = Square(5.0);
// This is also fine:
constexpr double another_square_again = alternative_square_routine(5.0);
// Even this is fine:
constexpr double cube = Cube(3.0);
}
MSVC 告诉我它涉及
this
指针,同时尝试 Codiva.io 中的代码(我猜它使用 GCC)给出了以下输出:
error: constexpr variable 'square_const' must be initialized by a constant expression
问题出在哪里?
在 P2280 之前,如果
this
在作为常量表达式一部分求值的 constexpr 函数内部使用,则只能在常量表达式求值中求值。
constexpr double square_const = Square(10.0);
是
的缩写constexpr double square_const = this->Square(10.0);
因为
Square
是一个非静态成员函数。在这里,您将评估 this
作为 square_const
初始化的一部分,您希望将其作为常量表达式(因为 constexpr
),而不是在作为常量表达式评估的一部分进行评估的 constexpr
函数中.
P2280 已被 C++23 接受,并作为 C++11 到 C++20 的缺陷报告。有了它,只要您不尝试访问
this
的值,就可以在此处使用 *this
。由于这是最近的缺陷报告,编译器可能还没有实现它。
仅使用
const
而不是 constexpr
不需要任何常量表达式评估,因此没有理由失败。
alternative_square_routine
可以,Cube
也可以,因为不涉及 this
。这些不是非静态成员函数。