mercredi 22 juillet 2015

Reordering members in a template by alignment

Assume I write the following code:

template<typename T1, typename T2>
struct pair {
  T1 first;
  T2 second;
};

What happens is that if I choose an instantiation of pair<char, int>, then as an object on the stack it will use more memory than pair<int,char> due to inefficient padding. Is there a way to use metaprogramming to "switch" the order of first and second in cases, where the alignment of the members causes less padding to be produced in the latter order? In other words, when I choose pair<char, int>, I would like the template to be generated from

template<typename T1, typename T2>
struct pair {
  T2 second;
  T1 first;
};

Aucun commentaire:

Enregistrer un commentaire