C + + uses templates to design a common message body

Source: Internet
Author: User

The server is made with C + +, the message protocol is divided into two kinds, the fixed-length message and the variable-length message. The game's message protocol is not complex: Baotou, player ID, player data.

    // 消息头        struct Base {        int size;        int id;        Base(int _id, int _size)            : id(_id), size(_size)            {}    };    // 常见的一个消息    struct RoleMsg : public Base {        enum { ID = 0x001 };        int PlayerID;        RoleProps prop;        RoleMsg()             : Base(ID, sizeof(*this))            , PlayerID(0)            {}    }

Each definition of a new normal message requires the writing of seven or eight lines of code. The structure of these messages is similar, and we can use the template to simplify the process of defining messages.

    // 模板消息    template <typename T, unsigned I>    struct StructTPL : public Base {        int CharID;        T prop;        StructTPL()            : Base(I, sizeof(*this))            {}    };        // 普通消息    typedef StructTPL <RoleProps, 0x1> RoleMsg;    typedef StructTPL <T2, 0x2> T2Msg;    typedef StructTPL <T3, 0x3> T2Msg;

With a template, a single line can define a new message, which is much simpler than the original.

Similarly, variable-length messages can also be defined using templates, without the need for detailed explanations.

C + + uses templates to design a common message body

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.