美文网首页
泛型模板编程

泛型模板编程

作者: 大啸 | 来源:发表于2020-05-27 14:04 被阅读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;

    }

    相关文章

      网友评论

          本文标题:泛型模板编程

          本文链接:https://www.haomeiwen.com/subject/ooswahtx.html