std::aligned_storage 的 C++03 替代方案
C++03 alternative for std::aligned_storage
自 C++11 以来,有一个专用模板结构 std::aligned_storage
和 alignas
关键字用于存储任何选定类型的对齐数据。我想知道是否可以为 C++03 支持的 std::aligned_storage
创建可移植的替代品。我想象的唯一方法是创建正确对齐的 (unsigned
) char
数组,但如何以正确的方式对齐它对我来说是一个很大的未知数
对于大多数类型,可以在 C++03 中实现 alignof
,例如,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;
}
自 C++11 以来,有一个专用模板结构 std::aligned_storage
和 alignas
关键字用于存储任何选定类型的对齐数据。我想知道是否可以为 C++03 支持的 std::aligned_storage
创建可移植的替代品。我想象的唯一方法是创建正确对齐的 (unsigned
) char
数组,但如何以正确的方式对齐它对我来说是一个很大的未知数
对于大多数类型,可以在 C++03 中实现 alignof
,例如,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;
}