提案P0595 希望加入一个新的 magic function 也就是 constexpr() 用来判断当前的函数是否在编译期执行,后来被更名为is_constant_evaluated并且进入 C++20。使用起来就像下面这样 constexpr int foo(int x) { if(std::is_constant_evaluated()) { return x; } else { return x + 1; } } 这样的话编译...
constexpr.demo.cpp:9:1: error: the value of ‘g’ is not usable in a constant expression } ^ constexpr.demo.cpp:2:5: note: ‘int g’ is not const int g; ^ constexpr.demo.cpp: At global scope: constexpr.demo.cpp:3:15: warning: inline function ‘constexpr int bar()’ used ...
int array2[func(10,20)]; // ERROR - func() is not a constexpr function. int array3[func_constexpr(10,rand())]; // ERROR - even though func_constexpr() is the 'constexpr' function, the expression 'constexpr(10,rand())' can't be evaluated at compile time. 1. 2. 3. 4. ...
constexpr.demo.cpp:9:1: error: the value of ‘g’ is not usable in a constant expression } ^ constexpr.demo.cpp:2:5: note: ‘int g’ is not const int g; ^ constexpr.demo.cpp: At global scope: constexpr.demo.cpp:3:15: warning: inline function ‘constexpr int bar()’ used ...
// Recursive constexpr function constexpr int fac(int n) { return n == 1 ? 1 : n*fac(n - 1); } // User-defined type class Foo { public: constexpr explicit Foo(int i) : _i(i) {} constexpr int GetValue() { return _i; ...
constT(&)[N]){returnN;}// Recursive constexpr functionconstexprintfac(intn){returnn==1?
{returnN; }// Recursive constexpr functionconstexprintfac(intn){returnn ==1?1: n * fac(n -1); }// User-defined typeclassFoo{public:constexprexplicitFoo(inti): _i(i){}constexprintGetValue()const{return_i; }private:int_i; };intmain(){// foo is const:constexprFoofoo(5);//...
(1)C++11中的constexpr指定的函数返回值和参数必须要保证是字面值,而且必须只有一行return代码,这给函数的设计者带来了更多的限制,比如通常只能通过return 三目运算符+递归来计算返回的字面值。 (2)C++14中只要保证返回值和参数是字面值就行了,函数体中可以加入更多的语句,方便了更灵活的计算。 它的字面意思是 c...
问为什么在constexpr函数中有“永不使用非文字类型”的规则?EN我在这里只是猜测,但可能是因为std::...
// uses a non-constexpr constructor. constexpr void f4(int x) { // Error, return type should not be void. return; } constexpr int f5(int x) { // Error, function body contains more than if (x<0) // return statement. x = -x; ...