复制、常量和非常量、getter 的优雅解决方案?

2022-01-23 00:00:00 constants c++

当你拥有它时你不讨厌它

Don't you hate it when you have

class Foobar {
public:
    Something& getSomething(int index) {
        // big, non-trivial chunk of code...
        return something;
    }

    const Something& getSomething(int index) const {
        // big, non-trivial chunk of code...
        return something;
    }
}

我们不能用另一个实现这两个方法,因为你不能从 const 版本调用非 const 版本(编译器错误).从非 const 版本调用 const 版本需要强制转换.

We can't implement either of this methods with the other one, because you can't call the non-const version from the const version (compiler error). A cast will be required to call the const version from the non-const one.

有没有真正优雅的解决方案,如果没有,最接近的解决方案是什么?

Is there a real elegant solution to this, if not, what is the closest to one?

推荐答案

我记得在一本 Effective C++ 书籍中,这样做的方法是通过从其他函数中丢弃 const 来实现非 const 版本.

I recall from one of the Effective C++ books that the way to do it is to implement the non-const version by casting away the const from the other function.

它不是特别漂亮,但很安全.由于调用它的成员函数是非常量的,因此对象本身也是非常量的,并且允许丢弃 const.

It's not particularly pretty, but it is safe. Since the member function calling it is non-const, the object itself is non-const, and casting away the const is allowed.

class Foo
{
public:
    const int& get() const
    {
        //non-trivial work
        return foo;
    }

    int& get()
    {
        return const_cast<int&>(const_cast<const Foo*>(this)->get());
    }
};

相关文章