c++ 常量表达式

const expression

任何表达式都有一种属性,类型。常量表达式即是表达式的一种类型。常量表达式指这种表达式能够在编译时刻被计算。

这种表达式,能被用到non-type模板参数,array sizes, 和其他需要const expression的地方。

int n = 1;
std::array<int, n> a1; // error, n is not a constant expression
const int cn = 2;
std::array<int, cn> a2; // OK, cn is a constant expression

core const expression

core const expression 是指所有子表达式不满足以下条件的表达式:

  1. 调用一个没有声明为constexpr的函数:

     constexpr int n = std::numeric_limits<int>::max(); // OK, max() is constexpr
     constexpr int m = std::time(NULL); // Error: std::time() is not constexpr
    
  2. 调用一个声明为constexpr的函数,但是没有定义函数体:
  3. 调用一个声明为constexpr的函数,但是,没有生成常量表达式。

     constexpr const int* addr(const int& ir) { return &ir; }
     static const int x = 5;
     constexpr const int* xp = addr(x); // OK
     constexpr const int* tp = addr(5); // error: &5 is not a constant expression
    
  4. A function call to a constexpr constructor with arguments that do not produce constant expressions in member-initializer lists that are called from this function

    int x;
    struct A {
        constexpr A(bool b) : m(b?42:x) { }
        int m;
    };
    constexpr int v = A(true).m; // OK
    constexpr int w = A(false).m; // error: non-const x
    
  5. ... ...

下面的情况是const expression(lvalue to rvalue转换 的表达式,大部分不是const expression):

有const限制符的int类型,并且用const expression 初始化

    int main() {
        const std::size_t tabsize = 50;
        int tab[tabsize]; // OK: tabsize is a constant expression

        std::size_t n = 50;
        const std::size_t sz = n;
        int tab2[sz]; // error: sz is not a constant expression
                      // because sz is not initialized with a constant expression
    }

... ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值