5

I'm trying to make my class 16-byte aligned with __declspec(align(16)); however it is a template class.

If I place __declspec(align(16)) before the template keyword, it tells me that variable attributes are not allowed there.

If I place it before the class keyword, the whole class becomes invalid and all methods show errors.

So how is it done then?

Casey
  • 41,449
  • 7
  • 95
  • 125
ulak blade
  • 2,515
  • 5
  • 37
  • 81
  • 2
    What about pasting the error messages and/or a minimal example? – arne Jun 28 '13 at 11:57
  • This might help, http://stackoverflow.com/questions/388934/aligning-member-variables-by-template-type or this http://stackoverflow.com/questions/2750832/c-parent-class-alignment – Caribou Jun 28 '13 at 12:07

1 Answers1

1

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 struct (which can be defined as a class of course), is 8-byte aligned, whereas the second struct is not aligned by itself, but rather each of the members is 8-byte aligned.

Daniel Trugman
  • 8,186
  • 20
  • 41