我在使用私有继承实现两个非常相关的类。 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!
是否有一个优雅的解决方案来重用私有基类的交换?
是否有更干净的方式来实现我在这里要做的事情(一个类的常量包装)?
您的意思是返回'iterator'(!而不是'const_iterator')为'begin'?否则,我没有看到有两个函数的意义,并重写派生类中的函数。 – 2010-10-27 18:36:57
'std :: vector <> :: begin() - > iterator'和'std :: vector <> :: begin()const - > const_iterator'。这正是我所做的,我的类具有类似的语义。我误解你的问题吗? – 2010-10-27 18:54:00
明白了,你是对的。但是,那么cbegin方法是什么呢? – 2010-10-27 18:55:57