包装器模式,又叫装饰者模式,英文叫Decorator Pattern。装饰模式是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
#include <iostream>
#include <boost/type_traits.hpp>
using namespace std;
class Myclass
{
public:
Myclass() {};
Myclass(int val): data(val) {}
~Myclass() = default;
void echo()
{
cout << data << endl;
}
private:
int data = 0;
};
template<typename T>
class Mywrapper
{
public:
typedef typename ::boost::remove_pointer<T>::type wrapped_type;
typedef wrapped_type* pointer_type;
typedef wrapped_type& reference_type;
private:
pointer_type m_ptr = nullptr;
protected:
Mywrapper(pointer_type p):m_ptr(p){}
Mywrapper(reference_type x):m_ptr(&x){}
~Mywrapper() = default;
public:
pointer_type get() const
{
return m_ptr;
}
};
class Class final: public Mywrapper<Myclass>
{
public:
typedef Mywrapper<Myclass> super_type;
typedef Class this_type;
Class(Myclass &m): super_type(m) {}
~Class() = default;
};
int main()
{
Myclass myclass(100);
Class class1(myclass);
class1.get()->echo();
return 0;
}
编译:
g++ -o test test.cpp -std=c++11 -I /usr/local/include/boost