Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 526
ulak blade Avatar asked Nov 13 '22 02:11

ulak blade


1 Answers

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.

like image 151
Daniel Trugman Avatar answered Nov 15 '22 05:11

Daniel Trugman