我正在为 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
变得暧昧了……
关于如何避免这种情况的任何想法?