jeudi 31 mars 2016

Metaprogramming for optimizing storage, C++

I'd like to generalize bitwise operators in C++ without thinking that the underlying structure is an array.

As instance... if I want to represent 86 bits i would use a structure structure/class like:

typedef struct {
 uint64_t x[1];
 uint16_t y[1];
 uint8_t z[1];
} sampleStruct;

Instead if i would like to allocate 160 bits I would use a structure like:

typedef struct {
 uint64_t x[2];
 uint32_t y[1];
} sampleStruct;

I guess a trivial, but not optimal solution for the storage would be to assume all chunks are uniform and allocate the minimum of those s.t. it covers the size I'm implementing, however even for a matter of exercise I prefer the way I exposed.

To me it sounds clear that I should use metaprogramming to solve the problem, so I have to properly define

template <int I>
typedef sampleStruct {
  //something
}

However I'm not a big expert on C++ template metaprogramming so i would like to understand what would be the best way to implement the different kind of sample struct varing I. I know how to decide the best "cover" for my length it would be something like:

N64 = I/64;
RemN = I%64;
if(0 < RemN <= 8) {
  add uint8_t var;
} else if (8 < RemN <= 16) {
  add uint16_t var;
} else if (16 < RemN <= 24) {
  add uint16_t var;
  add uint8_t var;
} else {
  //Similarly handle the other cases from 24 < RemN < 64
}

What can I do to achieve what I want to do?

Hoping it is clear enough... (Assume C++11 or more recent versions).

Aucun commentaire:

Enregistrer un commentaire