This question is specific to the MSVC compiler (specifically 2008), but I’m interested in non-compiler specific answers too.
I’m trying to figure out how to align a char buffer on the stack, based on the alignment of some arbitrary type. Ideally the code would read:
__declspec( align( __alignof(MyType) ) ) char buffer[16*sizeof(MyType)];
Unfortunately, this doesn’t work
error C2059: syntax error :
‘__builtin_alignof’
The compiler just doesn’t like the nested statements.
My only other idea is to do this:
char buffer[16*sizeof(MyType)+__alignof(MyType)-1];
char * alignedBuffer = (char*)((((unsigned long)buffer) + __alignof(MyType)-1)&~(__alignof(MyType)-1));
Does anyone know of a nicer way? It seems like the declspec thing should work, do I just have the syntax wrong or something?
Thanks for reading 🙂
Update
Check Robert Knight’s answer! Uses C++11 but is much cleaner than this…
Original Answer
How about this nasty hack:
Looks scary, but you need all that only once (preferably in some well hidden header file 🙂 ). Then you can use it in the following way:
StaticMem<T,N> array;can appear in the code, but also as a member of some bigger class (that’s how I use this hack) and should also behave correctly when allocated on the heap.Bug fix:
Line 6 of the example:
char data[_A_]corrected intochar data[size]