优雅的解决方案复制,const和非const,getter? [英] Elegant solution to duplicate, const and non-const, getters?
问题描述
你不要讨厌它
class Foobar {
public:
Something& ; getSomething(int index){
//大,非平凡的代码块...
return something;
}
const东西& getSomething(int index)const {
//大,非平凡的代码块...
return something;
}
}
其他一个,因为你不能从 const
版本(编译器错误)调用非 - const
需要从非 - const
调用 const
版本。 >
有没有一个真正优雅的解决方案,如果没有,最接近的是什么?
我记得从一个有效的C ++书中,做到这一点的方法是通过从其他函数转出const来实现非const版本。
这不是特别漂亮,但它是安全的。因为成员函数调用它是非常量,对象本身是非常量,允许转出const。
class Foo
{
public:
const int& get()const
{
//非平凡的工作
return foo;
}
int& get()
{
return const_cast< int&>(static_cast< const Foo *>(this) - > get
}
};
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;
}
}
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?
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.
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&>(static_cast<const Foo*>(this)->get());
}
};
这篇关于优雅的解决方案复制,const和非const,getter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!