在 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