What is a recommended way to overload the output stream operator? The following can not be done. It is expected that compilation will fail if the operator << is not defined for a type T.
template < class T >
inline std::ostream& operator << (std::ostream& os, const std::vector<T>& v)
{
os << "[";
for (std::vector<T>::const_iterator ii = v.begin(); ii != v.end(); ++ii)
{
os << " " << *ii;
}
os << " ]";
return os;
}
EDIT: It does compile, the problem was unrelated and was in the namespace. Thanks for assistance.
What is the vector in operator overloading? Explanation: It is a data type of class. It is defined as public static Vector operator + (Vector a, Vector b).
Overloaded operators are implemented as functions and can be member functions or global functions. Operator overloading involving vector types is not supported. An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator.
Notes: The relational operators ( == , != , > , < , >= , <= ), + , << , >> are overloaded as non-member functions, where the left operand could be a non- string object (such as C-string, cin , cout ); while = , [] , += are overloaded as member functions where the left operand must be a string object.
To overload an operator, we use a special operator function. We define the function inside the class or structure whose objects/variables we want the overloaded operator to work with.
This is what you want:
template < class T >
std::ostream& operator << (std::ostream& os, const std::vector<T>& v)
{
os << "[";
for (typename std::vector<T>::const_iterator ii = v.begin(); ii != v.end(); ++ii)
{
os << " " << *ii;
}
os << "]";
return os;
}
You forgot the std:: on the first ostream
You put an extra space after [
in os << "["
.
and you need typename
before std::vector<T>::const_iterator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With