lundi 1 janvier 2018

Properly align in-memory template, invariant of order of parameters

Take a look at this template.

template < typename T1, typename T2, typename T3 >
struct Alignement {
    T1 first;
    T2 second;
    T3 third;
};

int main() {
    Alignement<char, int, double> a1;
    Alignement<char, double, int> a2;
    assert( sizeof(a1) < sizeof(a2) );
    return 0;
}

Obviously assertion holds. Sub-optimal ordering leads to 50% more memory usage in this case.

My question is, what are the ways of combating it and properly ordering types in template structure, other than kindly asking user to take care of it himself (which would leave him with the same problem if he didn't know sizes of his types beforehand)?

My idea is to generate optimal ordering dynamically at compile time with macros or TMP, but I have no proper knowledge of these techniques. Or perhaps an army of partially specialized templates would get the job done?

The key aspect is preserving the AlignedObject.first syntax for client.

For my specific case, I'm looking for solution for exactly 3 parameters (3! possible orderings) but general solution (including variadic-length-templates) would be interesting to see.

Aucun commentaire:

Enregistrer un commentaire