Search code examples
c++stdlist

displaying a std::list<type*>


I have a little problem, because I'm making my school project and I need to create something like container witch is using std::list .

#include <iostream>
#include <list>

template<typename T>
class SomeContainer
{
    public:
        SomeContainer &operator[](size_t i) ;
        void push_back(const T &);
        std::list<T> someContent_;
}

class A
{
    //it doesn't matter whats inside
}

class B: public A
{}

class C: public A
{}

int main()
{
    SomeContainer <A*> something_;
    something_.push_back(new B);
    cout<< something [0];
}

I made something like this ,and there is a question. How can I display class A content, not the pointer to it? When I'm using int or string type everything works fine, but with <A*> even if I write

cout << *something[0];

It won't work.Thanks for help :)


Solution

  • Your operator[] has to have this signature:

    T &operator[](size_t i);
    T const& operator[](size_t i) const; // possibly const overload
    

    You want it to return a reference to one element of type T, not a container. But you'll need to iterate through the std::list, use rather std::vector for random access.

    Then, you'll be able to:

    cout << *something[0];
    

    (assuming you have operator<< for A overloaded).