私有继承和交换
我在两个非常相关的类的实现中使用私有继承。 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
的定义中,恶心!
是否有一个优雅的解决方案来重用私有基类的交换?
有没有一种更干净的方法来实现我在这里尝试做的事情(类的 const 包装器)?
I'm using private inheritance in the implementation of two very related classes. The using Base::X;
is very useful and elegant. However, I can't seem to find an elegant solution for reusing the base class's swap function.
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 )
{ /* ??? */ }
};
So far the only thing I can come up with is copy-pasting A::swap
's definition into Const_A::swap
's definition, YUCK!
Is there an elegant solution to to reuse the private base class's swap?
Is there a cleaner way to implement what I'm trying to do here (a const wrapper for a class)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像使用其余方法一样执行操作:
You can do as with the rest of the methods:
好吧,你不能直接调用
swap
的基础版本吗?代替
...
,您通常会交换仅与Const_A
有关的成员,而不是与A
相关的成员,但因为您的特定中没有任何成员如果是这样,这就是您所需要的。Well, can’t you just call the base’s version of
swap
?In place of
…
, you’d normally swap the members pertaining only toConst_A
, notA
but since there aren’t any in your particular case, this is all that you should need.