开发者

How to overload stream insertion operator with a template?

开发者 https://www.devze.com 2023-01-26 05:30 出处:网络
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.

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)'.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号