泛型模板编程

2020-05-27  本文已影响0人  大啸

#include <iostream>

#include <unordered_map>

#include <string>

class Top

{

public:

virtual void run(){}

virtual ~Top(){}

};

class Middle : public Top

{

void run() override { std::cout << "Middle\n"; }

};

class Buttom : public Top

{

void run() override { std::cout << "Buttom\n"; }

};

template<typename T>

class SmartPtr

{

public:

SmartPtr(T* realPtr) : ptr(realPtr){}

template<typename U>

SmartPtr(const SmartPtr<U>& other) : ptr(other.get()) {}

T* get() const { return ptr; }

template<typename U>

SmartPtr<T>* operator = (const SmartPtr<U>& other)

{

ptr = other.get();

return this;

}

T* operator -> ()

{

return ptr;

}

private:

T* ptr;

};

int main()

{

SmartPtr<Top> ptr1 = SmartPtr<Buttom>(new Buttom);

ptr1->run();

SmartPtr<Middle> ptr3(new Middle);

ptr1 = ptr3;

ptr1->run();

return 0;

}

上一篇 下一篇

猜你喜欢

热点阅读