Aligning member variables by template type

I want to align my member variables based on the type of the class template, but I'm not sure if this is really possible.

The following (very) simple example of what I would like to do

template<int Align> class MyClass { private: struct MyStruct { // Some stuff } __declspec(align(Align)); __declspec(align(Align)) int myAlignedVariable; }; 

So I would like Align to be a per-instance variable, and only through this would the value of the contents of the class be aligned.

Unfortunately, I always get the following error:

 error C2975: 'test::MyClass' : invalid template argument for 'Align', expected compile-time constant expression 

So, is this really possible or is alignment possible only using a fixed compile-time constant? If not, can anyone think of this?

Thanks:)

+2
source share
2 answers

Custom alignment is not part of the standard, so how compilers deal with it depends on them - it seems that VC ++ does not like to combine templates with __declspec.

I offer a job using specialization, something like this:

 template<int A> struct aligned; template<> struct aligned<1> { } __declspec(align(1)); template<> struct aligned<2> { } __declspec(align(2)); template<> struct aligned<4> { } __declspec(align(4)); template<> struct aligned<8> { } __declspec(align(8)); template<> struct aligned<16> { } __declspec(align(16)); template<> struct aligned<32> { } __declspec(align(32)); 

and then infer from this code:

 template<int Align> class MyClass { private: struct MyStruct : aligned<Align> { // stuff }; }; 

This, unfortunately, violates the POD version of MyStruct. It also does not work with inline / existing types, so you have to use a wrapper for them.

 aligned_t<int, 4> myAlignedVariable; 
+5
source

Boost has already solved this problem. They use the technique in boost :: optional (a reference to the header ), which should contain enough space for an aligned arbitrary type, but cannot (will not) actually create an instance of this object during construction.

Their solution was to allocate a simple pool of bytes (a char array) and use a new place to create objects in the right place. The address specified for the new location can be any arbitrary alignment.

By saying this, you are saying that in your question you are giving a very simple example. What is the actual problem that you are trying to solve by implementing a class in which each member has a user-defined alignment that does not change for each member, but can change in every instance of the class?

+3
source

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


All Articles