c++ - 私有(private)继承和交换

标签 c++ private-inheritance

我在两个非常相关的类的实现中使用私有(private)继承。 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!

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

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

最佳答案

那么,你不能只调用基础版本的 swap 吗?

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

代替 ,您通常会交换仅属于 Const_A 的成员,而不是 A,但是因为没有任何成员在您的特定情况下,这就是您所需要的。

关于c++ - 私有(private)继承和交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4036464/

相关文章:

c# - 如何从 C++ DLL 导出全局变量?

C++ 异常和来自 std::exception 的继承

c++ - 如何转换为私有(private)派生的子类型?

c++ - 我可以使用 C 风格的转换将派生类转换为私有(private)基类吗?

c++ - 从抽象(纯虚拟)类私有(private)继承是否有意义?

c++ - 错误的私有(private)基类无法访问?

c++ - 函数模板的模板参数名是否可以在函数参数列表中多次使用?

c++ - 几乎 pod 数据的 reinterpret_cast(布局兼容性是否足够)

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 如何提供来自外部源的字符串,例如来自 C++ 的 HTTP 请求