1

我在两个非常相关的类的实现中使用私有继承。这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::swapConst_A::swap' 的定义中,太糟糕了!

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

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

4

2 回答 2

5
于 2010-10-27T18:34:21.473 回答
3

You can do as with the rest of the methods:

void Const_A::swap( Const_A& other ) {
   A::swap(other);
   // here any specifics
}
于 2010-10-27T18:36:10.770 回答