Contexpr and constant expressions
contexpr function
[test1.cpp]
1#include <iostream>2 using namespacestd;3 4constexprintScreenintX//constexpr5 {6 returnx;7 }8 9 intMain ()Ten { One Const intx =0;//Const, which is a constant expression because the value does not change Aconstexprintz = screen (x);//constexpr -cout << z<<Endl; - return 0; the}
[test2.cpp]
1#include <iostream>2 using namespacestd;3 4constexprintScreenintx)5 {6 returnx;7 }8 9 intMain ()Ten { One intx =0;//is not a constant expression because the value changes A intz =Screen (x); -cout << z<<Endl; - return 0; the}
(1) [test1.cpp] conforms to the general usage of the CONSTEXPR function, that is, the return type of the function and all formal parameter types must be literal types (the literal type is the type of the result that the compilation process can get). At this point, if it turns out to be an const int x = 0;
int x = 0;
error, because the screen function is used in a context that requires a constant expression (a variable of type constexpr must be initialized with a constant expression), the compiler checks that the return value of the function is not a constant expression during compilation. If not, you will get an error.
(2) [test2.cpp] means that the CONSTEXPR function can return a non-const expression, the compilation process is not an error, because the screen function is not used in a context that requires constant expression, the compiler is compiling the process does not check the function's return value, will not error.
(3) as a supplement, it is important to note that the CONSTEXPR function must have a return statement.
• If the context of a constant expression is not required, such as: int z = screen(x);
you can not return a constant expression, the compiler does not check whether the result of the function returns a constant expression.
• If you are in a context that requires a constant expression, such as: constexpr int z = screen(x);
then, the CONSTEXPR function must return a constant expression. At this point the compiler goes to check that the function returned is not a constant expression, and if not, it will be an error.
Contexpr constructor function
C + + Primer seventh 5. CONTEXPR usage