我怎样才能以通用的方式打印任何容器的内容?

Ara*_*raK 9 c++ templates stl operator-overloading

我正在尝试使用C++模板编写一段代码以获得乐趣.

#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;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码没有编译:)

在1,2,3处产生相同的错误:错误C2593:'operator <<'是不明确的

我想要做的就是重载<<运算符以使用任何容器.那有意义吗 ?怎么可能呢?如果可能的话,如果不是为什么?

编辑::感谢更正:)'sth'方式是一个很好的解决方案.

我很好奇,如果我们可以使用C++ 0x Concepts,这种模糊性 - 如Neil解释的那样 - 会消失吗?

jon*_*son 7

您可以通过指定Container模板参数本身是模板化来限制operator <<仅应用于模板化容器.由于C++ std容器也有一个allocator模板参数,因此您还必须将其作为Container的模板参数包含在内.

template
    < typename T
    , template<typename ELEM, typename ALLOC=std::allocator<ELEM> > class Container
    >
std::ostream& operator<< (std::ostream& o, const Container<T>& container)
{
    typename Container<T>::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;
}
Run Code Online (Sandbox Code Playgroud)