当调用来自同一个非const版本的重载成员函数时,是否可以删除const限定符?

dch*_*tri 6 c++ user-interface const

例如:

struct B{};

struct A {

 const B& findB() const { /* some non trivial code */ }

 // B& findB() { /* the same non trivial code */ }

 B& findB() { 
       const A& a = *this;
       const B& b = a.findB();
       return const_cast<B&>(b);
  }
};
Run Code Online (Sandbox Code Playgroud)

问题是我想避免在常量findB和非常量findB成员函数中重复相同的逻辑.

Jon*_*rdy 7

是的,您可以将对象强制转换为const,调用const版本,然后将结果转换为非const:

return const_cast<B&>(static_cast<const A*>(this)->findB());
Run Code Online (Sandbox Code Playgroud)

const只有在最初没有声明有问题的对象时,才能安全地抛弃const.由于您处于非const成员函数中,因此您可以知道这种情况,但这取决于实现.考虑:

class A {
public:

    A(int value) : value(value) {}

    // Safe: const int -> const int&
    const int& get() const {
        return value;
    }

    // Clearly unsafe: const int -> int&
    int& get() {
        return const_cast<int&>(static_cast<const A*>(this)->get());
    }

private:
    const int value;
};
Run Code Online (Sandbox Code Playgroud)

一般来说,我的会员职能很短,所以重复是可以容忍的.您有时可以将实现分解为私有模板成员函数,并从两个版本调用它.

  • "既然你使用非const方法,你就知道情况就是这样." 你什么意思?非`constst`方法可以很好地返回一个`const`对象. (2认同)
  • 如果你有一个私有辅助函数,并且它不是一个const-member函数,那么如何在不删除常量的情况下从const-version中调用它?我如何从常量public成员函数中调用该非常量私有辅助函数.难道它还不会抱怨它的恒定吗? (2认同)