c++ - 使用函数外部的 const 变量计算时,Constexpr 不会被求值

标签 c++ constexpr

我提供了两个代码片段,其中一个可以编译,另一个则不能。

无法编译的:

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:

  1. 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/

相关文章:

c++ - 在运行时重写相同的类方法 C++

c++ - Eigen:有效地将矩阵评估的输出存储在原始指针中

c++ - 声明一个 constexpr initializer_list 对象是否合法?

c++ - gcc v10 和 v9 : bug or feature 之间的 constexpr 差异

c++ - 传递 constexpr 函数以在编译时使用

c++ - 非 constexpr 可构造类的 constexpr 成员函数

c++ - 解释这个c++代码

c++ - 将元素插入具有设定值的 map 并打印集合

c++ - (隐式声明)不能被引用——它是一个被删除的函数

c++ - 由于模板基类,从不完整类型初始化静态 constexpr