C++ Collection of different types of static elements
Greetings! Unfortunately my C++ is not very good. For an embedded system, I need to implement the task using ONLY STATIC memory allocation.
There are several groups of registers that have a virtual address. I made a primitive description of the register group like this:
using RegisterType = uint32_t;
template <uint8_t cnt, uint16_t addr>
class Registers
{
public:
uint16_t count {cnt}; //Must be declared before data
uint16_t startAddr {addr}; //Must be declared before data
RegisterType data[cnt];
};
Next, I need a collection of these groups. I made a primitive description of the collection like this:
template <uint8_t cnt>
class RegistersGroup
{
public:
Registers<0, 0>* group[cnt];// I really don’t like this type cast
};
This code works:
int main()
{
Registers<5, 0x0000> r1;
Registers<2, 0x00FF> r2;
RegistersGroup<2> g;
r1.data[0] = 11;
r1.data[1] = 12;
r1.data[2] = 13;
r1.data[3] = 14;
r1.data[4] = 15;
r2.data[0] = 11;
r2.data[1] = 22;
g.group[0] = (Registers<0, 0>*)&r1;
g.group[1] = (Registers<0, 0>*)&r2;
std::cout<<r1.count<<std::endl;
std::cout<<r2.count<<std::endl;
std::cout<<g.group[0]->startAddr<<std::endl;
for (size_t i = 0; i < g.group[0]->count; ++i)
std::cout<<g.group[0]->data[i]<<std::endl;
std::cout<<g.group[1]->startAddr<<std::endl;
for (size_t i = 0; i < g.group[1]->count; ++i)
std::cout<<g.group[1]->data[i]<<std::endl;
return 0;
}
But it only works when declaring the fields "count", "startAddr" before the field "data", since in the class "RegistersGroup" the type is reduced to "Registers<0, 0>". I'm not sure if this code will work on other compiler versions and platforms. Is it possible to make the solution more beautiful?