tips for constexpr and Constant Expressions

来源:互联网 发布:python 分析网页 编辑:程序博客网 时间:2024/06/07 03:27

A constant expression is an expression whose value cannot change and that can be evaluated at compile time.

A typical characteristic: the constant express will be evaluated at compile time, not at run time.

So when we use it and pay attention to it.. If we are implicitly to know what it is, don't use it.

for instant:

#include <iostream>int main(){int m = 10;constexpr int m2 = m;std::cout << m2 << std::endl;return 0;}

when we compile it, it can't work it out.? Why?

It's easy to explain it. Because of the "m" variables are not usable when compiling. The compiler don't recognize it.. 

your compiler will tell you it's not usable in constant expression. Mine tell me that.. But if we told the compiler that "m" is a ”const int“

It will work out or to be compiled successfully..

so let we made some changes:

#include <iostream>int main(){const m = 10;constexpr int m2 = m;std::cout << m2 << std::endl;return 0;}

I'm a cookie. There are a lot of concepts in the C++ world. It baffles me...

for example: const definition contain the "low-level const" and "top-level const". if they are both existed in the expression or statements, we can igonre the "top-level const".

How to distinguish it? C++ prime tells me that " Top-level const can appear in any object type, ...., Low-level const appears in the base type of compound types such as pointers or references. Note the pointer types, unlike most other types, can have both top-level and low-level const independently."

Another words: "... Like an object defined outside any function, these special local objects also have fixed addresses. Therefore, a constexpr reference may be bound to, and a constexpr pointer may address, such variables. "

0 0
原创粉丝点击