可以实现
alignof
在C++ 03中,对于大多数类型,例如有一个很长的解释。
this page
。
有了它,您可以使用一些模板专门化来使用具有这种对齐方式的存储类型:
#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;
}