I am looking for better solutions on how to organize and access my data. My data is a set of structures (_array_10
and _array_20
in the example below) that contain std::array
of different sizes (see my_data
below). Ideally, I would like to access it as it was an array of structs with different lengths, but this is not allowed, since different lengths are different types. The solution I have below works, but I find it extremely ugly (specially the array of void *
).
Q1. Any ideas on how to have a safer, more efficient/portable, or at least less ugly solution?
Q2. Is the proposed solution without templates portable? It relies on the fact that the length is stored before the rest of the data, since casting the pointer to an object with wrong length would mess the access to all fields that come after the first field of variable length.
My limitations include:
- C++11
- standard libraries
- no
std::vector
- memory usage prevents me from being able to simply allocate an array of
my_data
with the maximum possible length - the bulk of the data (
_array_10
,_array_20
, etc) will be placed in a memory area reserved specially for it
#include <iostream>
#include <array>
std::array<void *, 2> _ptrs;
template<int length>
struct my_data
{
int array_length;
std::array<int, length> something;
std::array<int, length> data;
my_data()
{
array_length = length;
}
};
template<int length>
void
print_element(int array_idx, int element)
{
my_data<length> * ptr = reinterpret_cast<my_data<length> *>(_ptrs[array_idx]);
std::cout << "array " << length << ", data[" << element << "] = " << ptr->data[element] << ".\n";
}
void
print_element(int array_idx, int element)
{
my_data<1> * ptr = reinterpret_cast<my_data<1> *>(_ptrs[array_idx]);
int length = ptr->array_length;
int data_to_print = 0;
switch (length)
{
case 10:
{
data_to_print = reinterpret_cast<my_data<10> *>(_ptrs[array_idx])->data[element];
break;
}
case 20:
{
data_to_print = reinterpret_cast<my_data<20> *>(_ptrs[array_idx])->data[element];
break;
}
}
std::cout << "array " << length << ", data[" << element << "] = " << data_to_print << ".\n";
}
int main()
{
my_data<10> _array_10;
my_data<20> _array_20;
_ptrs[0] = static_cast<void *>(&_array_10);
_ptrs[1] = static_cast<void *>(&_array_20);
_array_10.data[5] = 11;
_array_20.data[5] = 22;
std::cout << "using template\n";
print_element<10>(0,5);
print_element<20>(1,5);
std::cout << "\nwithout template\n";
print_element(0,5);
print_element(1,5);
}
Aucun commentaire:
Enregistrer un commentaire