Wednesday, May 9, 2018

Vector of Smart Pointers

#include <iostream>
#include <vector>
#include <memory>


// Require C++ version 14 to compile!

class Base
{
public:
    Base(Base & other);
    Base(Base *);
    Base(char const * const tag, char const * const desc) : m_tag(tag), m_desc(desc) {}

    void print();

public:
    std::string m_tag = "";
    std::string m_desc = "";
};



Base::Base(Base & rhs)
{
    m_tag = rhs.m_tag;
    m_desc = rhs.m_desc;
}


Base::Base(Base *pOther)
{
    m_tag = pOther->m_tag;
    m_desc = pOther->m_desc;
}


void Base::print()
{
    std::cout << __FUNCTION__ << "(" << this << "): Base::m_tag = " << m_tag << std::endl 
              << "                  Base::m_desc = " << m_desc << std::endl;
}


template <class CNAME>
Base * createClass(char const *const tag, char const * const desc)
{
    CNAME *pObj = new CNAME(tag,desc);

    Base *pBase = dynamic_cast<Base*>(pObj);

    return pBase;
}




class KelasA : public Base
{
public:

    KelasA(char const * const tag, char const * const desc) : Base(tag, desc) {}
    void FuncA() {}
};

class KelasB : public Base
{
public:
    KelasB(char const * const tag, char const * const desc) : Base("B", desc) {}
    void FuncA() {}
};


int main()
{
    std::vector<std::unique_ptr<Base>> vb;

    std::unique_ptr<Base> p;
    p = std::make_unique<Base>((createClass<KelasA>("A", "Kelas A-1")));
    vb.push_back(std::move(p));
    p = std::make_unique<Base>((createClass<KelasB>("B", "Kelas B-1")));
    vb.push_back(std::move(p));

    for(auto v = vb.begin(); v != vb.end(); v++)
    {
        (*v)->print();
    }

    return 0;
}

No comments:

Post a Comment