c++ 常量表达式

来源:互联网 发布:知乎hfp护肤品怎么样 编辑:程序博客网 时间:2024/06/06 05:50

const expression

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

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

int n = 1;std::array<int, n> a1; // error, n is not a constant expressionconst 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; // OKconstexpr 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
原创粉丝点击