Retrieve data from heterogeneous std::list

前端 未结 4 1758
孤城傲影
孤城傲影 2021-01-24 20:14

In the below code I am simply trying to experiment with a Heterogeneous std::list where I have stored three Derived class object in a list of type Base*. When retrieving data fr

4条回答
  •  清酒与你
    2021-01-24 20:38

    #include 
    #include 
    #include 
    #include 
    
    class Base;
    typedef std::list any_list;
    
    class Base{
    public:
        virtual ~Base(){}
        virtual std::string getData()=0;
    };
    
    class Derived1 : public Base
    {
    public:
        std::string s;
        Derived1():s("D1"){}
        std::string getData()
        {
            return s;
        }
    };
    class Derived2 : public Base
    {
    public:
        std::string s;
        Derived2():s("D2"){}
        std::string getData()
        {
            return s;
        }
    };
    class Derived3 : public Base
    {
    public:
        std::string s;
        Derived3():s("D3"){}
        std::string getData()
        {
            return s;
        }
    };
    
    int main(int argc, char **argv) {
        any_list l;
        l.push_back(new Derived1);
        l.push_back(new Derived2);
        l.push_back(new Derived3);
    
        for(any_list::iterator itr=l.begin();itr!=l.end();++itr)
            std::cout<<((Base*)*itr)->getData()<

    Thanks for the help. Confusion is clear and the problem is solved. By d way what is -

    typedef std::list< std::unique_ptr > any_list;

    I didn't find anything called unique_ptr in std:: namespace. :(

提交回复
热议问题