我提供了两个代码片段,其中一个可以编译,另一个则不能。
无法编译的:
class Solution {
public:
const int MAX_NUM = 100;
const int MAX_SIZE = 200;
bool canPartition(vector<int>& nums) {
bitset<(MAX_NUM*MAX_SIZE)/2 + 1> bits(1);
int sum = 0;
for(int num: nums)
{
sum += num;
bits |= bits << num;
}
return !(sum % 2) and bits[sum/2];
}
};
给出错误:
错误:非类型模板参数不是常量表达式
仅在调用“constexpr”成员函数的计算中才允许隐式使用“this”指针
这样做的一个:
class Solution {
public:
bool canPartition(vector<int>& nums) {
const int MAX_NUM = 100;
const int MAX_SIZE = 200;
bitset<(MAX_NUM*MAX_SIZE)/2 + 1> bits(1);
int sum = 0;
for(int num: nums)
{
sum += num;
bits |= bits << num;
}
return !(sum % 2) and bits[sum/2];
}
};
我阅读了 constexpr
文档并发现了这里可能存在问题的两件事:
constexpr must immediately initialized.
It must have constant destruction, i.e. it is not of class type
您能指出这里的问题并帮助我理解问题吗?
最佳答案
错误消息很好地解释了发生的情况。 bits
声明的模板参数需要是一个常量表达式。但是,如果您使用非静态成员,例如 MAX_NUM
在非 constexpr 成员函数内,您最终会计算 this
指针,这是不允许的。 ref :
A core constant expression is any expression whose evaluation would not evaluate any one of the following:
block 引用>
- the
this
pointer, except in a constexpr function that is being evaluated as part of the expression当变量像
MAX_NUM
时在成员函数内部声明,它们不是类的成员,因此可以用作常量表达式,这就是第一个版本编译的原因。
关于c++ - 使用函数外部的 const 变量计算时,Constexpr 不会被求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69145522/