可能重复: How do I remove code duplication between similar const and non-const member functions?
在下面的例子:
template<typename Type, unsigned int Size>
class MyClass
{
public: inline Type& operator[](const unsigned int i)
{return _data[i];}
public: inline const Type& operator[](const unsigned int i) const
{return _data[i];}
protected: Type _data[Size];
};
的常量和非const operator[]
独立地实现。
在设计方面是它最好有:
如果解决方案2)是更好的,这将是给定的例子的代码?
你不能既拥有执行调用另一个没有虚掷常量性,这是一个坏主意。
该const
方法不能调用非const
之一。
非const
方法不应该调用const
之一,因为它会需要转换的返回类型。
这是公知的和被广泛接受的实现模式中,当非const方法通过其常量对应实现,如在
class some_class {
const some_type& some_method(arg) const
{
...;
return something;
}
some_type& some_method(arg)
{
return const_cast<some_type&>(
const_cast<const some_class *>(this)->some_method(arg));
}
};
这是一种非常有效的技术,其基本上具有在情况没有可比性(在便利)替代时,方法主体相对较重。 const_cast
的恶比重复的代码邪恶显著小。
然而,当方法的主体基本上是一个内胆,它可能是一个更好的主意,坚持明确的实施相同,只是为了避免const_cast
s这种勉强可读的堆积。
一个也许可以想出沿的线而实施的正式更好的设计castless解决方案
class some_class {
template <typename R, typename C>
static R& some_method(C *self, arg)
{
// Implement it here in terms of `self->...` and `R` result type
}
const some_type& some_method(arg) const
{
return some_method<const some_type>(this, arg);
}
some_type& some_method(arg)
{
return some_method<some_type>(this, arg);
}
};
但对我来说,它看起来比const_cast
的做法甚至更少优雅。
不幸的是,“不变性”模板不工作,但我仍然认为这是值得考虑的总体思路:
// NOTE: this DOES NOT (yet?) work!
template <const CV>
Type CV& operator[](unsigned int index) CV {
...
}
暂时,我会实现琐碎的功能只是两次。如果代码变得比任何一个或两个线条更加复杂,我会因素的细节到一个函数模板,并委托执行。