问为什么在constexpr函数中有“永不使用非文字类型”的规则?EN我在这里只是猜测,但可能是因为std::string s = "abc"是一个自动变量,并在函数开始时在堆栈中分配(即使还没有构造)违反了constexpr规则吗?
the address past the end of such an object ([expr.add]), the address of a non-immediate fu...
提案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; } } 这样的话编译...
// 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; return x; } 将函数模板声明为constexpr函数时,如果...
return true; if (TREE_THIS_VOLATILE (t)) { if (flags & tf_error) error ("expression %qE has side-effects", t); return false; } if (CONSTANT_CLASS_P (t)) return true; switch (TREE_CODE (t)) { case FUNCTION_DECL: case BASELINK: ...
// 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; ...
例: const int max = 20; // max是常量表达式 const int maxx = max+1; //maxx是常量表达...
void function1() { x=100; // OK. } void function2() const { x=100; // ERROR. The const methods can't change the values of object fields. } }; 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. constexpr是一个不同的概念。如果将编译时常量作为参数传递,则它将一个函...
return true; if (TREE_THIS_VOLATILE (t)) { if (flags & tf_error) error ("expression %qE has side-effects", t); return false; } if (CONSTANT_CLASS_P (t)) return true; switch (TREE_CODE (t)) { case FUNCTION_DECL: case BASELINK: ...
{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);//...