C++11 constant expression
#define_crt_secure_no_warnings#include<iostream>#include<string>#include<vector>#include<map>/** Constant expression is primarily to allow some computations to occur at compile time, that is, when code is compiled rather than running. * This is a great optimization: if something can be done at compile time, it will be done only once, not every time the program runs. *//*limitations of the CONSTEXPR function: only one return statement (with very few exceptions) in a function must return a value (cannot be a void function) must have been defined before use function, global data that cannot use a very high expression in a return statement expression and must be a constant expression*/constexprintGetconst () {return 3;}//err, there can be only one return statement in the functionconstexprintdata () {constexprinti =1; returni;} constexprintdata2 () {//a constexpr function that allows only one line of executable code to be included//However, the inclusion of TypeDef, using directives, static assertions, etc. is allowed. Static_assert (1,"fail"); return -;}intA =3; constexprintdata3 () {returnA//err, return returns the function, global data, in a statement expression that cannot be used with a very-expressed expression}/*the constructor of a constant expression has the following limitations: The function body must be an empty initialization list can only be assigned by a constant expression*/structdate{constexpr Date (intYintMintD): Year (y), month (m), day (d) {} constexprintGetYear () {returnYear ;} constexprintGetMonth () {returnMonth;} constexprintGetDay () {returnDay ;}Private: intYear ; intmonth; intDay ;};voidmytest () {intArr[getconst ()] = {0}; enumYes =Getconst (), E2}; constexprintnum =Getconst (); constexprintFunc ();//function declaration, which is defined after the functionconstexprintc = func ();//err, cannot be compiled, must have been defined before useconstexpr Date Prcfound {1949,Ten,1}; constexprintFoundmonth =Prcfound.getmonth (); Std::cout<< foundmonth << Std::endl;//Ten return;} constexprintfunc () {return 1;}intMain () {mytest (); System ("Pause"); return 0;}
C++11 constant expression