我在两个非常相关的类的实现中使用私有(private)继承。 using Base::X;
非常有用和优雅。然而,我似乎无法找到一个优雅的解决方案来重用基类的交换功能。
class A
{
public:
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
A clone();
void swap( A& other );
};
class Const_A : private A
{
public:
// I think using A::A; will be valid in C++0x
Const_A( const A& copy) : A(copy) { }
// very elegant, concise, meaningful
using A::cbegin;
// I'd love to write using A::begin;, but I only want the const overload
// this is just forwarding to the const overload, still elegant
const_iterator begin() const
{ return A::begin(); }
// A little more work than just forwarding the function but still uber simple
Const_A clone()
{ return Const_A(A::clone()); }
// What should I do here?
void swap( Const_A& other )
{ /* ??? */ }
};
到目前为止,我唯一能想到的就是将 A::swap
的定义复制粘贴到 Const_A::swap
的定义中,YUCK!
是否有一个优雅的解决方案来重用私有(private)基类的交换?
是否有更简洁的方法来实现我在这里尝试做的事情(一个类的 const 包装器)?
最佳答案
那么,你不能只调用基础版本的 swap
吗?
void swap( Const_A& other )
{
A::swap(other); // swaps the `A` portion of `this`.
// …
}
代替 …
,您通常会交换仅属于 Const_A
的成员,而不是 A
,但是因为没有任何成员在您的特定情况下,这就是您所需要的。
关于c++ - 私有(private)继承和交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4036464/