mardi 3 octobre 2017

Const array of objects with member variable = sum of previous indexes member variable

Is it possible to create a const array of objects where one member variable is the sum of a member variable in the objects created before it?

class Data
{
public:
    constexpr Data(uint32_t offset, uint32_t length) :
        m_offset(offset), m_length(length)
    {
    }

    uint32_t m_offset; //would like this to be calculated at compile time
    uint32_t m_length;
};

const Data dataList[] =
{
    Data(0, 10),
    Data(10, 25),
    Data(35, 20)
};

offset is the sum of the length of all previous objects in the array (10 + 25 = 35 in index 2).

I'd like to avoid having to manually calculate the offset.

I've played around with std::integral_constant and recursive calls to constexpr, but nothing seems close enough to a working solution to share. Any guidance is much appreciated!

Aucun commentaire:

Enregistrer un commentaire