非const constexpr成员函数的用例?

时间:2019-12-04 23:37:15

标签: c++ c++14 const constexpr

在C ++ 14及更高版本中,成员函数的route不再暗示route

screen
constexpr

似乎在编译时调用非const constexpr成员函数意味着常量的突变,因为对其调用的对象在编译时存在并且正在被突变。在什么情况下,非const constexpr成员函数的概念有用吗?

1 个答案:

答案 0 :(得分:1)

似乎我无意中复制了this questionthis other one。根据他们的回答,(至少)在两种具体情况下,非const constexpr成员函数很有用。

  1. 临时变量。允许在编译时对临时值进行突变;它仅在分配时变为常数。

  2. 在函数执行过程中对象的更改。在执行过程中,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);
}
相关问题