0

I want to pack my C++ class structure with msgpack using some polymorphous mechanism to apply code packing base classes only once.

Currently, I am packing the data twice, in the base class and in the subclass.

This is my current status:

class Base {

    public:
        template <typename Packer>
        void msgpack_pack(Packer& pk) const
        {
            pk.pack_map(1);

            pk.pack("key");
            pk.pack("value");
        }
};

class Subclass : public Base {

    public:
        template <typename Packer>
        void msgpack_pack(Packer& pk) const
        {
            pk.pack_map(2);

            // code repetition
            pk.pack("key");
            pk.pack("value");
            //////////////////

            pk.pack("child_key");
            pk.pack("child_value");
        }
};

I want to get rid of the lines in between "code repetition" but I am currently now aware of how to achieve this. Would be nice if someone had an idea.

Duck Dodgers
  • 3,409
  • 8
  • 29
  • 43
Robert_Jordan
  • 256
  • 4
  • 13

1 Answers1

2

You might factorize and call base class. but it need some split before:

class Base
{
protected:
    template <typename Packer>
    void msgpack_pack_content(Packer& pk) const
    {
        pk.pack("key");
        pk.pack("value");
    }
public:
    template <typename Packer>
    void msgpack_pack(Packer& pk) const
    {
        pk.pack_map(1);
        msgpack_pack_content(pk);
    }
};

class Subclass : public Base {
    template <typename Packer>
    void msgpack_pack_content(Packer& pk) const
    {
        Base::msgpack_pack_content(pk);
        //////////////////

        pk.pack("child_key");
        pk.pack("child_value");
    }
public:
    template <typename Packer>
    void msgpack_pack(Packer& pk) const
    {
        pk.pack_map(2);

        msgpack_pack_content(pk);
    }
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Thank you. This is almost the solution I tried before but without templating "msgpack_pack_content" so msgpack could not recognize some custom members of "Subclass". But this way it works. – Robert_Jordan Jan 15 '19 at 09:42