2010-10-27 96 views
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::swap的定义为Const_A::swap的定义,YUCK!

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

是否有更干净的方式来实现我在这里要做的事情(一个类的常量包装)?

+0

您的意思是返回'iterator'(!而不是'const_iterator')为'begin'?否则,我没有看到有两个函数的意义,并重写派生类中的函数。 – 2010-10-27 18:36:57

+0

'std :: vector <> :: begin() - > iterator'和'std :: vector <> :: begin()const - > const_iterator'。这正是我所做的,我的类具有类似的语义。我误解你的问题吗? – 2010-10-27 18:54:00

+0

明白了,你是对的。但是,那么cbegin方法是什么呢? – 2010-10-27 18:55:57

回答

5

那么,难道你不能只是调用基地的版本swap

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

在地方,您通常会交换仅与Const_A,不A成员,但由于没有任何你的具体情况,这是所有你应该需要。

+0

'Const_A'不能转换为'A'。 – 2010-10-27 18:38:20

+5

@caspin:是的,它是:你在* Const_A内*,Const_A本身知道它可以转换为'A',即使世界其他地方都没有。 – 2010-10-27 18:39:40

3

你可以做与方法的其余部分:

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