How to overload stream insertion operator with a template?
I am trying to overload the stream insertion operator so can I print std::vector to std::cout, but I'm having problem with syntax.
This is what I tried:
template<typename T> std::ostream & operator<<(std::ostream &os, std::vector<T> &v)
{
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(os, ', '));
开发者_高级运维return os;
};
And I wanted to use it like this:
std::vector<float> v(3, 1.f);
std::cout << v;
What is the correct syntax for that kind of operator overloading?
The code is almost fine, however :
- The separator
', 'is incorrect : use", " - Your function could (and should) take a const reference to v :
const std::vector<T> &v - There is an unnecessary
;after the function close brace :)
For the record, ', ' is a multi-character constant of type int so the compiler complains that no overload of std::ostream_iterator constructor matches the argument list '(std::ostream, int)'.
加载中,请稍侯......
精彩评论