C++ ostream implicitly deleted with template

前端 未结 1 696
梦谈多话
梦谈多话 2021-01-21 08:35

I have a templated class that I am trying to print out using operator << but get the errors:

Vertex.h:24:16: error: use of deleted function \'std::basic_os         


        
相关标签:
1条回答
  • 2021-01-21 08:37

    std::ostream and siblings doesn't have copy constructors and copy assignment operators[1], and when you made the following possibly typoed code

    std::ostream operator<<(std::ostream& ost, const Vertex<T>& v) {
    // ^ Returning by value
        ost << v.getItem();
        return ost;
    }
    

    you are actually trying to return a copy of ost. To fix that, you must return the stream by reference.

    std::ostream& operator<<(std::ostream& ost, const Vertex<T>& v) {
    //          ^ This
    

    [1] In C++11, they are actually marked as =deleted

    0 讨论(0)
提交回复
热议问题