Alex Rivera | Logout

How could I print the contents of any container in a generic way?

Asked 2009-07-20T15:21:21.353
14

I am trying to write a piece of code for fun using C++ templates.

#include <iostream>
#include <vector>

template <class Container>
std::ostream& operator<<(std::ostream& o, const Container& container)
{
    typename Container::const_iterator beg = container.begin();

    o << "["; // 1

    while(beg != container.end())
    {
        o << " " << *beg++; // 2
    }

    o << " ]"; // 3

    return o;
}

int main()
{
    std::vector<int> list;

    list.push_back(0);
    list.push_back(0);

    std::cout << list;

    return 0;
}

The above code doesn't compile :)

At 1, 2, 3 the same error is produced : error C2593: 'operator <<' is ambiguous

All what I am trying to do is overloading the << operator to work with any container. Does that make sense ? How would that be done If possible, if not why ?

EDIT :: Thanks for corrections :) 'sth' way is a good solution.

I am just curious if this ambiguity -as Neil explained- would go away if we could use C++0x Concepts ?

Edit
Report

1 Answer

3

What is the error? I saw one, you need a typename:

typename Container::iterator beg = container.begin();

What happens here is that the compiler doesn't know anything about Container when it is first reading it. So we have to give it a little help and tell it that iterator will be a type(syntactically it could be any valid name at class scope, so a function, variable,...). When writing a template method, any type that depends on the template type must specify that it is a type with the keyword typename.

answered 2009-07-20T15:22:55.403

Your Answer