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

前端 未结 4 552
别跟我提以往
别跟我提以往 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条回答
  •  后悔当初
    2021-01-22 19:02

    Declaring template could be dangerous as this template includes 'all' variable types int, char etc. Due to this compiler does not know which operator<< to use.

    In order to take only container type variables use template of templates. Here is working code for you

    template class Container>
    std::ostream& operator<<(std::ostream& out, const Container>& c) {
        for (auto item : c) {
            out << item << " ";
        } 
        return out;
    }
    
    int main()
    {
        cout << "Hello world" << endl;
        int arr[] = { 0,3,6,7 };
        vector v(arr, arr+4);
        cout << v << endl;
        return 0;
    }
    

提交回复
热议问题