AnO*_*hew 5 c++ constants constexpr c++14
在 C++14 及更高版本中,constexpr
for 成员函数不再意味着const
。
struct Value\n{\n int i = 5;\n\n constexpr bool not_five() // requires const to compile\n {\n return this->i != 5;\n }\n};\n\nint main()\n{\n constexpr Value v{6};\n static_assert(v.not_five());\n}\n
Run Code Online (Sandbox Code Playgroud)\n\nerror: passing \xe2\x80\x98const Value\xe2\x80\x99 as \xe2\x80\x98this\xe2\x80\x99 argument discards qualifiers [-fpermissive]\n static_assert(v.not_five());\n ^\n
Run Code Online (Sandbox Code Playgroud)\n\n似乎在编译时调用非常量 constexpr 成员函数意味着常量的突变,因为它所调用的对象在编译时存在并且正在发生突变。非常量 constexpr 成员函数的概念在什么情况下有用?
\n看来我无意中重复了这个问题以及另一个问题。根据他们的答案,(至少)有两个具体场景可以使用非常量 constexpr 成员函数。
临时突变。允许在编译时改变临时值;它仅在分配时才变为常量。
函数执行期间对象的突变。在执行时,constexpr 函数可能会创建一个对象实例,然后通过成员函数对其进行变异。这些成员函数不能在编译时调用,除非它们是 constexpr,但如果它们是 const,则它们不能改变所调用的实例。
struct Value
{
int i{};
constexpr Value add(int n)
{
this->i += n;
return *this;
}
constexpr Value add(Value other) const
{
Value ret{this->i};
ret.add(other.i); // call to non-const constexpr member
return ret;
}
};
int main()
{
constexpr Value v = Value{}.add(1);
// v.add(1); // illegal
constexpr Value u = v.add(v);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
166 次 |
最近记录: |