c – 使用std :: aligned_storage对齐静态数组

前端之家收集整理的这篇文章主要介绍了c – 使用std :: aligned_storage对齐静态数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用std :: aligned_storage模式实现简单静态数组的16字节对齐:
  1. #include <type_traits>
  2. int main()
  3. {
  4. const size_t SIZE = 8;
  5. using float_16 = std::aligned_storage<sizeof(float) * SIZE,16>::type;
  6. float_16 mas;
  7. new(&mas) float[SIZE];//Placement new. Is this necessary?
  8.  
  9. mas[0]=1.f;//Compile error while attempting to set elements of aligned array
  10. }

我得到以下编译错误

no match for «operator[]» in «mas[0]»

然后我尝试使用显式指针转换:

  1. float* mas_ = reinterpret_cast<float*>(mas);

但这也会产生编译错误

invalid cast from type «float_16 {aka std::aligned_storage<32u,
16u>::type}» to type «float*»

任何人都可以建议我如何正确使用std :: aligned_storage对齐静态数组?

解决方法

你可以使用:
  1. float* floats = new (&mas) float[SIZE];

然后你可以使用:

  1. floats[0] = 1.f;

根本没有reinterpret_cast

猜你在找的C&C++相关文章