TAGS :Viewed: 15 - Published at: a few seconds ago

[ Overloading << operator to store data ]

First of, I've been searching all around for my particular problem but I havent' been able to find any answers. So, what I want to do is to overload the << operator so that I could do:

myObj = new MyObj();
unsigned int v = 2; 
myObj &lt;&lt; v;

Keeping in mind that this would make that, using this class:

class MyObj{
private:
  char *data;
  int count;

public:
  MyObj(){ data = new char[64]; count = 0; }
  //This "is" the overloaded &lt;&lt; method
  template &lt;typename T&gt;
  T&amp; operator&lt;&lt;(T val){
    *(T*)(data + count) = val;
    count += sizeof(T);
  }
}

The effect should be the same as this (suppossing data is a public attribute):

myObj &lt;&lt; v;

Should be the same as

*(unsigned int*)(myObj.data + myObj.count) = v;
myObj.count += sizeof(v);

Any ideas on how to do it? I have only find ways to overload the I/O or bit operators, but anything like this.

Thank you!

Answer 1


If I understand correctly, you have

MyObj *myObj;
......
myObj = new MyObj();
unsigned int v = 2; 
myObj << v;

To be able to use << like that, you usually have:

MyObj myObj;
......
unsigned int v = 2; 
myObj << v;

or you could use:

myObj = new MyObj();
unsigned int v = 2;
(*myObj) << v;

If you want to be able to write code like myObj << u << v, you further need:

....
    template <typename T>
    MyObj& operator<<(T val){
        *(T*)(data + count) = val;
        count += sizeof(T);
        return *this;
    }
....