Search code examples
c++variadic-templates

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.


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.