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

Elegant solution to duplicate, const and non-const, getters?(复制、常量和非常量、getter 的优雅解决方案?)
本文介绍了复制、常量和非常量、getter 的优雅解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你拥有它时你不讨厌它

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());
    }
};

这篇关于复制、常量和非常量、getter 的优雅解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)