How can I overload serialize boost function to have one for file storing and another for tcp messages?

StackOverflow https://stackoverflow.com/questions/23417630

  •  13-07-2023
  •  | 
  •  

質問

I have class and I have implemented serialize function like (this is what I use to store on file and deserialize from file)

    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        ar & id;
        ar & first_name;
        ar & last_name;
        ar & salary;
        ar & username;
// and lot of more data
        ar & data;
    }

What I need in addition to serialize just couple members (not all, for example id, username, salary) to char array (for sending over tcp like message) and deserialize back (on client side). How can I overload serialize to have one for file storing and another for tcp messages ?

役に立ちましたか?

解決

You can create your own Archive classes and then specialize the serialize() function template for your classes:

template<>
void serialize(MyBriefOutputArchive& ar, const unsigned int version) {
  // Alternative serialization.
}

template<>
void serialize(MyBriefInputArchive& ar, const unsigned int version) {
  // Alternative deserialization.
}

To make your own archive classes, you can subclass or copy the Boost classes so they otherwise work identically. Be careful because some archive classes, like boost::binary_oarchive and boost::binary_iarchive, have header comments that say they shouldn't be subclassed - you should copy their implementation instead (which is simple as all the work is done in their superclass).

If you use some template meta-programming tricks, you can recognize your own archive class within the generic serialize() without the need for specializations. This would be preferred under the DRY principle, but it might be easier to get things working with specializations first.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top