私有继承和交换

def*_*ode 1 c++ private-inheritance

我在两个非常相关的类的实现中使用私有继承.这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 )
   { /* ??? */ }
};
Run Code Online (Sandbox Code Playgroud)

到目前为止,我唯一能想到的就是将复制粘贴A::swap的定义转换为Const_A::swap定义,YUCK!

是否有一个优雅的解决方案来重用私有基类的交换?

有没有更简洁的方法来实现我在这里尝试做的事情(一个类的const包装器)?

Kon*_*lph 5

好吧,你能不能只打电话给基地的版本swap

void swap( Const_A& other )
{
    A::swap(other); // swaps the `A` portion of `this`.
    // …
}
Run Code Online (Sandbox Code Playgroud)

取而代之的是,您通常会交换仅属于的成员Const_A,A但由于在您的特定情况下没有任何成员,这就是您应该需要的全部内容.

  • @caspin:是的,它是:你在*`Const_A`里面,而`Const_A`本身知道它可以转换成'A`,即使世界其他地方没有. (5认同)