1

我正在为 pimpl 习惯用法创建一个实用程序类,但是我有一些问题希望得到一些帮助:

这就是我所拥有的:
[sehe:另请参见此处的 rev.1:https ://gist.github.com/1379569/9f6cca5703e6195da65e34103393d901dde3b1bf ]

pimpl.h

template<typename T>
class pimpl
{
    template <typename> friend class pimpl;

    pimpl(const pimpl& other);
    pimpl(pimpl&& other);
    pimpl& operator=(const pimpl& other);
    pimpl& operator=(pimpl&& other);    
protected:

    ~pimpl();

    struct implementation;
    std::unique_ptr<implementation> impl_;
public:
    pimpl();

    template<typename P0>
    pimpl(P0&& p0);

    pimpl(const T& other);
    pimpl(T&& other);

    void swap(T& other);
};

pimpl_impl.h

// #include "pimpl.h" // TODO add header guards...

template<typename T>
pimpl<T>::pimpl() : impl_(new implementation()){}

template<typename T>
template<typename P0>
pimpl<T>::pimpl(P0&& p0) : impl_(new implementation(std::forward<P0>(p0))){}

template<typename T>
pimpl<T>::~pimpl(){}

template<typename T>
pimpl<T>::pimpl(const T& other) : impl_(new implementation(*((pimpl&)other).impl_)){}

template<typename T>
pimpl<T>::pimpl(T&& other) : impl_(std::move(((pimpl&)other).impl_)){}

template<typename T>
void pimpl<T>::swap(T& other)
{
    impl_.swap(other.impl_);
}

这就是你使用它的方式:

A.h

#include "pimpl.h"

class A : public pimpl<A>
{
    A();
    A(const A& other);
    A(A&& other);
    virtual ~A();
    void foo();
};

A.cpp

#include "A.h"
#include "pimpl_impl.h"

template<>
struct pimpl<A>::implementation
{
     void foo()
     {
     }
};

A::A() : pimpl(){}
A::A(const A& other) : pimpl(other){}
A::A(A&& other) : pimpl(std::move(other)){}
A::~A(){}
void A::foo(){impl_->foo();}

这工作得很好,但是当您将继承放入图片时它很快就会崩溃:

class B : public pimpl<B>, public A
{
    ...
};

B::B() : pimpl() {} // pimpl ambiguous

pimpl变得暧昧了……

关于如何避免这种情况的任何想法?

4

1 回答 1

4

虽然由于 Liskov,我不建议将 pimpl 填充到一个好奇的基类中,但我认为让它工作没有任何真正的问题。

就像@Nim 建议的那样:在做的时候似乎一切都很好

class B : public pimpl<B>, public A
{
    B() : pimpl<B>() {} 
};

Gist 更新了适用于 B 的完整示例代码:

溴化氢

#include "A.h"

class B : public pimpl<B>, public A
{
  public:
    B();
    B(const B& other);
    B(B&& other);
    virtual ~B();
    void bar();
};

B.cpp

#include "pimpl_impl.h"
#include "B.h"

template<>
struct pimpl<B>::implementation
{
     void bar()
     {
     }
};

B::B() : pimpl<B>(){}
B::B(const B& other) : pimpl<B>(other){}
B::B(B&& other) : pimpl<B>(std::move(other)){}
B::~B(){}
void B::bar(){ pimpl<B>::impl_->bar();}

主.cpp:

#include "B.h"

int main()
{
    A a;
    B b;
}
于 2011-11-20T00:13:06.227 回答