aligned_storage
通过union 将存储和访问分开,并将存储数据的内存作为整体进行对齐
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include <vector> #include <iostream> #include <type_traits>
template <typename T> using Vec = std::vector<T>;
template <typename T, size_t N> struct GetAlignedData { using type = typename std::aligned_storage<sizeof(T) * N, sizeof(T) * N>::type; };
template <typename T, size_t N> using AlignedType = typename GetAlignedData<T, N>::type;
template <typename T, size_t N> union PackData { AlignedType<T, N> storage; T elem[N]; };
int main() { PackData<int, 4> data; int x[4] = {1, 2, 3, 4}; data.storage = *(reinterpret_cast <AlignedType<int, 4>* >(x)); for(auto z : data.elem) { std::cout << "z: " << z << std::endl; } return 0; }
|