2

I have the following code:

ostream.write(reinterpret_cast<const char*>(&bone.parent_index), sizeof(bone.parent_index));

Now this is a lot of code for something that should be fairly straightforward and simple. I'm wondering if there exists a way to write functionally the same thing with less code; it'd be preferable to have an interface like this:

ostream.write(bone.parent_index);

I'm open to any solution within the C++11 standard library or boost.

Colin Basnett
  • 4,052
  • 2
  • 30
  • 49
  • 3
    But, but... that's just 1 line of code! Well, you can always write a wrapper function... – SingerOfTheFall May 23 '14 at 06:24
  • It can always be smaller ;) I'd prefer not to roll my own wrapper if there exists one that I can use in a trusted library. – Colin Basnett May 23 '14 at 06:27
  • 1
    You can spend a lot of time making one line smaller, or you can write a wrapper function (@SingerOfTheFall) and go back to adding value to your program. I have hit this problem in all the languages I have used, its always a different case though. – miltonb May 23 '14 at 06:47
  • like this? http://stackoverflow.com/questions/1559254/are-there-binary-memory-streams-in-c – 9dan May 23 '14 at 06:55
  • 1
    I think the binary copy is dangerous whenever the memory model changes between media, also structures that don't store all their members by value are rare. If you have only flat data and no crossing of system boundaries, my answer below may help. – Wolf May 23 '14 at 07:11
  • +1 BTW: The code snippet tells me that you have to serialize a rather complicated structure with a lot of references? I'm curious about the next answers :) – Wolf May 23 '14 at 07:29

1 Answers1

4

For simple types (and structures that store all their attributes by values), a template method will work fine, that wraps the objects automatically:

class MyOStreamAdapter 
{
    template <class ObjType>
    MyOStreamAdapter& write(const ObjType& obj) {
        ostream.write(reinterpret_cast<const char*>(&obj), sizeof obj));
        return *this;
    }
    // ...
}

within an adapter that takes an ostream when created. You use it like this

char c = 8;
float f = 8.1;
int i = 99:
MyOStreamAdapter os(ostream);
os.write(c);
os.write(f);
os.write(i);

or this:

char c = 8;
float f = 8.1;
int i = 99:
MyOStreamAdapter os(ostream);
os.write(c).write(f).write(i);

This approach is limited: In the real world, you'll need probably class specific serializing methods. Also keep in mind that steams may connect to systems with different memory layout (endinanness).

Wolf
  • 9,679
  • 7
  • 62
  • 108