"natural_alignment_of" type_trait?

174 Views Asked by At

In C++11, we now have the alignas keyword, which can be used to define a new type that is simply an existing type, but with stricter alignment, for example by typedef:

typedef char Maximally_Aligned_Char alignas( max_align_t );

Is there a way programmatically, given a typename T, to determine the original, "natural" alignment of the type? Something like the following conceptual natural_alignment_of type_trait that would compile:

size_t natural_char_alignment = natural_alignment_of< Maximally_Aligned_Char >::value;
static_assert( natural_char_alignment == alignof( char ) );

Background:

I'm writing templated code to act on all scalar-types. Generally with integers, ( sizeof( T ) == alignof( T ) ) is true, but with official alignas support, I don't think I can make this assumption anymore.

Speculation:

Perhaps something like std::decay would work? Testing code, I see that G++4.8 warns about "ignoring attributes on template argument", which sounds nice and dangerous.

1

There are 1 best solutions below

5
On

I honestly do not understand what you could do with your natural_alignment trait.

If I define a type with an alignment of 16, then I expect all instances of this type to have an alignment of 16. You are not allowed to break this contract.

Since you already know about alignof, then why don't you simply use it ? Even though in theory one could conceivably use non-power of 2 alignments, in practice it would be extremely brittle, so all you have to do is to take std::max(sizeof(T), alignof(T)) as a basis for your computations and off you go.

Note: it might mean that the data is packed less tightly, and padding is introduced, but why should you care ? You did your best within the user's constraints.