C++ print template container error (error: ambiguous overload for 'operator<<') understanding?

前端 未结 4 554
别跟我提以往
别跟我提以往 2021-01-22 18:35

I want to write template function which can print container like std::vector, std::list.

Below is my function, just overload <<.

4条回答
  •  -上瘾入骨i
    2021-01-22 19:08

    The problem is that the templated type Container can match any type, not just containers. That includes the " " you are trying to print.

    If you look at the error message from a different compiler: https://godbolt.org/g/3YKtca

    :5:15: note: candidate function [with Container = char [2]]
    
    std::ostream& operator<<(std::ostream& out, const Container& c){
    

    Perhaps you want a partial specialization of vector to only take vectors. Determining if a type is a container is a more complicated problem.

    #include 
    #include 
    
    template
    std::ostream& operator<<(std::ostream& out, const std::vector& c){
        for(auto item:c){
            out< iVec{5, 9, 1, 4, 6};
        std::cout<

    https://godbolt.org/g/NJNwmN

提交回复
热议问题