Reputation: 71
Its open season on #defines and other macros and I was looking at a portable way of aligning structures 32 bit and 64 bit code. Previously the code had a #define AMD64 and padding was added when this was not the case.
Is this a portable way of doing the same, minus the #if !defined(...) ... #endif
constexpr size_t defaultAlignmentBits = 4u;
constexpr size_t defaultAlignmentBytes = 16u;
template<size_t padLen>
struct PadIfNonZero {
uint8_t pad[padLen];
};
template<>
struct PadIfNonZero<0> {
};
template<typename T>
using PadToAlignment = PadIfNonZero<(sizeof(T) % defaultAlignmentBytes == 0 ? 0 : defaultAlignmentBytes - sizeof(T) % defaultAlignmentBytes)>;
And how can this be improved?
Upvotes: 0
Views: 62
Reputation: 48
If you want your classes and structs to have a certain alignment in memory you should look into the alignas operator. It works like this:
Class Foo
alignas(64)
{
Foo();
~Foo();
};
Here the class Foo is aligned to 64 bytes. But note that alignas is only available in c++11 or above. Hope this helps!
Upvotes: 2