Elegant solution to duplicate, const and non-const, getters?(复制、常量和非常量、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 的优雅解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:复制、常量和非常量、getter 的优雅解决方案?
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
