代码之家  ›  专栏  ›  技术社区  ›  deft_code

私人继承和交换

  •  1
  • deft_code  · 技术社区  · 15 年前

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

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

    有没有更清晰的方法来实现我在这里要做的事情(类的常量包装)?

    2 回复  |  直到 13 年前
        1
  •  5
  •   Konrad Rudolph    15 年前

    好吧,你不能称之为 swap ?

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

    代替 … ,您通常交换只属于 Const_A 不是 A 但由于在您的特定案例中没有任何问题,这就是您应该需要的全部内容。

        2
  •  3
  •   David Rodríguez - dribeas    15 年前

    您可以使用其他方法:

    void Const_A::swap( Const_A& other ) {
       A::swap(other);
       // here any specifics
    }