小编AnO*_*hew的帖子

非常量 constexpr 成员函数的用例?

在 C++14 及更高版本中,constexprfor 成员函数不再意味着const

\n\n
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\n
error: 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

c++ constants constexpr c++14

5
推荐指数
1
解决办法
166
查看次数

标签 统计

c++ ×1

c++14 ×1

constants ×1

constexpr ×1