dimanche 13 septembre 2020

Templated typedef structs with constructor in C++

I have this code right now, which seems to work so far but I was wondering if there was a way to get the exact same struct in a more elegant way since my method so far needs a duplicate everytime for each struct... The end goal would be to have a typedefed struct which would swap the bytes according to the endianness automatically.

using ResourceHeader_t = struct ResourceHeader_s 
{
    uint32_t magic;
    uint32_t chunkVersion;
    uint32_t chunkSize;
};

template<bool bigEndian>
struct ResourceHeader : public ResourceHeader_s 
{
    ResourceHeader(ResourceHeader_t* ptr) : ResourceHeader_s(*ptr)
    {
        if (bigEndian)
        {
            LITTLE_BIG_SWAP(magic);
            LITTLE_BIG_SWAP(chunkVersion);
            LITTLE_BIG_SWAP(chunkSize);
        }
    }
};

Usage example :

ResourceHeader<true> resourceHeader((ResourceHeader_t *)fileBuffer);

Aucun commentaire:

Enregistrer un commentaire