包裝器模式,又叫裝飾者模式,英文叫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