Since C++11 there is a dedicated template struct std::aligned_storage and alignas keyword for storing aligned data of any chosen type. I am wondering if it is possible to create portable replacement for std::aligned_storage that is supported in C++03. The only way I imagine this is creating properly aligned (unsigned) char array, but how to align it in a right way is a great unknown for me
-
3Like, boost.org/doc/libs/1_57_0/libs/type_traits/doc/html/…Cheers and hth. - Alf– Cheers and hth. - Alf2018-07-26 13:18:20 +00:00Commented Jul 26, 2018 at 13:18
-
@Cheersandhth.-Alf I can read the code, but I'd love to understand why does it work the way it doesbartop– bartop2018-07-26 13:27:26 +00:00Commented Jul 26, 2018 at 13:27
Add a comment
|
1 Answer
It is possible to implement alignof in C++03 for most types, for example there is a long explanation on this page.
With that, you could use a storage type with that alignment using some template specializations:
#include<iostream>
struct alignment {};
template<>
struct alignment<1> {
typedef char type;
static const unsigned div_v=sizeof(type);
static const unsigned add_v=div_v-1;
};
template<>
struct alignment<2> {
typedef short type;
static const unsigned div_v=sizeof(type);
static const unsigned add_v=div_v-1;
};
template<>
struct alignment<4> {
typedef int type;
static const unsigned div_v=sizeof(type);
static const unsigned add_v=div_v-1;
};
template<>
struct alignment<8> {
typedef double type;
static const unsigned div_v=sizeof(type);
static const unsigned add_v=div_v-1;
};
template<typename T>
struct align_store {
typedef alignment<__alignof(T)> ah;
typename ah::type data[(ah::add_v + sizeof(T))/ah::div_v];
};
int main() {
std::cout << __alignof(align_store<int>) << std::endl;
std::cout << __alignof(align_store<double>) << std::endl;
}
9 Comments
bartop
Alignof may be quite useful, but how does it get me closer to alignas or aligned_storageDutow
Edited my answer - if you know the alignment of the type, you could use a storage type with the same alignment.
bartop
It helps me a bit, but I would be thankful if You could give an example of how implement aligned storage having this
alignof operatorrubenvb
Without
alignas you'll still need a way to get the actual pointer to the memory where your object should live inside your aligned_store.rubenvb
@Dutow it is not aligned properly.
data is large enough to contain the alignment padding followed by an aligned object. But &data will generally not point to a properly aligned memory block in and of itself. Same goes for std::aligned_storage. |