Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ ostream implicitly deleted with template

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_ostream<char>::basic_ostream(const std::basic_ostream<char>&)'

where line 24 refers to the return of the output operator in the following code:

/In declaration of templated class Vertex
friend std::ostream operator<<(std::ostream& ost, const Vertex<T>& v) {
    ost << v.getItem();
    return ost;
}

//In main function
Vertex<int>* v1 = new Vertex<int>();
v1->setItem(15);
cout << *v1 << endl;

How can I get this output working?

like image 342
cjbrooks12 Avatar asked Nov 28 '13 04:11

cjbrooks12


1 Answers

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

like image 159
Mark Garcia Avatar answered Sep 19 '22 04:09

Mark Garcia