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

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

    mas[0]=1.f;//Compile error while attempting to set elements of aligned array
}

我得到以下编译错误

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

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

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对齐静态数组?

解决方法

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

然后你可以使用:

floats[0] = 1.f;

根本没有reinterpret_cast 原文链接:https://www.f2er.com/c/116241.html

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