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.

6
  • 3
    But, but... that's just 1 line of code! Well, you can always write a wrapper function... Commented May 23, 2014 at 6: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. Commented May 23, 2014 at 6: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. Commented May 23, 2014 at 6:47
  • like this? stackoverflow.com/questions/1559254/… Commented May 23, 2014 at 6: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. Commented May 23, 2014 at 7:11

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments