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++ - 如果我不清除 stringstream 会发生什么?

c++ - 如何使用 WinCrypt 和 C++ 以 PEM 格式导入私钥?

c++ - 有什么方法可以用 MSVS2015 模拟编译时双常量吗?

c++ - 如何使用函数初始化静态常量成员

c++ - 使用 OpenGL 版本 3+ 渲染文本/UI

c++ - 在 CLion 中使用 GLib

c++ - "surprising"常量初始化因为定义顺序

c++ - 模板;构造函数;编译时间

C++ 强制非 constexpr 上下文

c++11 - 如何定义 constexpr 变量