Reputation: 2665
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?
Upvotes: 6
Views: 1945
Reputation: 195
Put the alignment declaration after the class
keyword and before the class's name:
template<typename xyz>
class __declspec(align(16)) myclass
{
...
};
Upvotes: 0
Reputation: 8501
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.
Upvotes: 1