How do you use __declspec (align (16)) with a template?

I am trying to make my class 16-byte aligned with __declspec(align(16)) ; however, this is a template class.

If I put __declspec(align(16)) in front of the template keyword, it tells me that variable attributes are not allowed there.

If I put it in front of the class keyword, the whole class becomes invalid and all methods show errors.

So how is this done?

+4
source share
1 answer

This implementation probably answers this request:

 template <class T, std::size_t Align> struct alignas(Align) aligned_storage { T a; T b; }; template <class T, std::size_t Align> struct aligned_storage_members { alignas(Align) T a; alignas(Align) T b; }; int main(int argc, char *argv[]) { aligned_storage<uint32_t, 8> as; std::cout << &as.a << " " << &as.b << std::endl; aligned_storage_members<uint32_t, 8> am; std::cout << &am.a << " " << &am.b << std::endl; } // Output: 0x73d4b7aa0b20 0x73d4b7aa0b24 0x73d4b7aa0b30 0x73d4b7aa0b38 

The first structure (which can be defined as a class, of course) is 8-byte aligned , while the second structure is not aligned on its own, but rather each of the 8-byte members is aligned .

0
source

Source: https://habr.com/ru/post/1488674/


All Articles