Overloading << with the struct (no class) cout style

I have a structure that I would like to output using "std :: cout" or another output stream. Is this possible without using classes?

thank

#include <iostream>
#include <fstream>
template <typename T>
struct point{
  T x;
  T y;
};

template <typename T>
std::ostream& dump(std::ostream &o,point<T> p) const{
  o<<"x: " << p.x <<"\ty: " << p.y <<std::endl;
}


template<typename T>
std::ostream& operator << (std::ostream &o,const point<T> &a){
  return dump(o,a);
}


int main(){
  point<double> p;
  p.x=0.1;
  p.y=0.3;
  dump(std::cout,p);
  std::cout << p ;//how?
  return 0;
}

I tried a different syntax, but I can't get it to work.

+3
source share
2 answers

This may be a copy-paste error, but there are only a few errors. Firstly, there may not be free functions const, but you have marked dumpas such. The second error is that it dumpdoes not return a value, which is also easily fixed. Fix those and it should work:

template <typename T> // note, might as well take p as const-reference
std::ostream& dump(std::ostream &o, const point<T>& p)
{
    return o << "x: " << p.x << "\ty: " << p.y << std::endl;
}
+9

++, , , . , , , ++.

-, "" - .

template<typename T>
std::ostream& operator << (std::ostream &o, const point<T> &a)
  {
  o << "x: " << a.x << "\ty: " << a.y << std::endl;
  return o;
  }
+7

Source: https://habr.com/ru/post/1742935/


All Articles