C ++ operator overload example

Well, I'm new to operator overloading, and I found this problem. Instead of documenting myself, I prefer to ask you: D

The fact is that I know how to perform overloading using an operator, but I ran into problems with stacking operators. I will try to give a relatively simple example:

struct dxfdat
{
 int a;
 string b;

 /* here is the question */
}

/* use: */
dxfdat example;

example << "lalala" << 483 << "puff" << 1029 << endl;

"lalala" << 483 << "puff" << 1029 << endlstored in b.

dxfdat& operator<< (T a), and such things work with one parameter (example << 7), but I would like it to work with cout.

Sorry to be so lazy.

EDIT:

The real thing ... Well, this is a little more complicated ... in fact, b is not a string, but a vector of other objects, but example << "lalala" << 483 << "puff" << 1029 << endlshould just create only one object.

, (), , , ( , ?):

struct dxfDato
{
    dxfDato(int c = 0, string v = 0, int t = 0) { cod = c; val= v; ty = t; }

    int ty;
    int cod;
    string val;
};

struct dxfItem
{
    int cl;
    string val;
    vector<dxfDato> dats;
    vector<dxfItem> sons;

    template <class T>
    dxfItem &operator<<(const T &t)
    {
        dxfDato dd;
        std::stringstream ss;
        ss << t;
        val = ss;
        dats.push_back(dd); // this way, it creates a lot of objects
        return d;
    }

};

dxfItem headers;

headers << "lalala" << 54789 << "sdfa" << 483 << endl;
// this should create *just one object* in dats vector,
// and put everything on string val

,

. , , .

( , , , , stackoverflow)

+1
3

, :)

: std::cout - std::endl.

, , .

struct EndMarker {};
extern const EndMarker end; // To be defined in a .cpp

class Data
{
public:
  Data(): m_data(1, "") {}

  // Usual operator
  template <class T>
  Data& operator<<(const T& input)
  {
    std::ostringstream aStream;
    aStream << input;
    m_data.back() += aStream.str();
  };

  // End of object
  Data& operator<<(EndMarker) { m_data.push_back(""); }

private:
  std::vector<std::string> m_data;
}; // class Data

, .

:

Data data;
data << 1 << "bla" << 2 << end << 3 << "foo" << end;

// data.m_data now is
// ["1bla2", "3foo", ""]

() , end , , ( ).

, ... .

+1

, operator << - , "".

class me {

    me& operator<<(int t) {...; return *this;}
};

me m;
m << 4 << 5 << 6;

, ( , )!

+7
template <typename T>
dxfdata & operator <<( dxfdata & d, const T & t ) {
   std::ostringstream os;
   os << t;
   d.b += os.str();
   return d;
}
+2

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


All Articles