Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ How to call the methods of a template variadic type list inside a method of the class which derived from that list?

So I want a class which allows a sequence of classes to call their decode/encode methods in that way:

/// This class manages the decoding/encoding of a sequence of binary fields.
template <typename Derived, typename... Fields >
struct BinarySequence : Fields...
{
    using Super = BinarySequence;

    bool decode(const char* buffer, size_t& length)
    {
        return true && Fields...::decode(buffer, length);
    }

    bool encode(char* buffer, size_t& length)
    {
        return true && Fields...::encode(buffer, length);
    }
};

The issue is to call Fields...::decode(buffer, length) is not the correct way. If I have BinarySequence< MessageType, MessageSender, MessageTimeStamp >, I want its decoder to do the same as

bool decode(const char* buffer, size_t& length)
{
    return MessageType::decode(buffer, length) && MessageSender::decode(buffer, length) && MessageTimeStamp::decode(buffer, length);
}

What would be the right way to do so? I use Visual Studio Code 2017.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Have a look at fold expressions. The correct syntax is:

/// This class manages the decoding/encoding of a sequence of binary fields.
template <typename Derived, typename... Fields >
struct BinarySequence : Fields...
{
    using Super = BinarySequence;

    bool decode(const char* buffer, size_t& length)
    {
        return (Fields::decode(buffer, length) && ...);
    }

    bool encode(char* buffer, size_t& length)
    {
        return (Fields::encode(buffer, length) && ...);
    }
};

This requires C++17 or newer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading