Send data with winsock

Started by
29 comments, last by hplus0603 19 years, 4 months ago
Don't you hate it when you have to add everything in two places?

MyClass::Input( InStream & is ) {  is >> member1;  is >> member2;  is >> member3;}MyClass::Output( OutStream & os ) {  os << member1;  os << member2;  os << member3;}


If you forget just one change in one of the places, you'll have a bug and have a hard time finding it.

Instead, I like creating policy objects that use verb objects for actions:

template< class Action > MyClassMarshalPolicy {    MyClass & mc_;  public:    MyClassMarshalPolicy( MyClass & mc ) : mc_( mc ) {}    void operator()( Action & a ) {      a( mc_.member1 );      a( mc_.member2 );      a( mc_.member3 );    }};class InputStreamer {    InStream & is_;  public:    InputStreamer( InStream & is ) : is_( is ) {}    template< class T >    void operator()( T & t ) {       is_ >> t;    }};class OutputStreamer {    OutStream & os_;  public:    OutputStreamer( OutStream & os ) : os_( os ) {}    template< class T >    void operator()( T & t ) {       os_ << t;    }};


It looks like the second way is more work initially, but you re-use the InputStreamer and OutputStreamer for all your objects. Also, you can easily create other streamer objects to use for the policy, and still have all of the users automatically update to take advantage of new members you add.

I've done this to do generic input/output to/from binary, text, XML and Lua, for example, and it works very well. You may want to annotate your members with some meta-data, like name, and desired precision, but that's an easy extension.
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement