C++ constexpr 到位对齐的存储结构

C++ constexpr in place aligned storage construction

本文关键字:存储 结构 对齐 constexpr C++      更新时间:2023-10-16

我正在尝试制作一个对齐的变体类型,该变体类型使用 std::aligned_storage 来保存数据。有没有办法以 constexpr 的方式就地构造一个对象?我读到你不能做新的 constexpr 放置。

#include <iostream>
#include <string>

struct foo
{
    foo(std::string a, float b)
    : bar1(a), bar2(b)
    {}
    std::string bar1;
    float bar2;
};

struct aligned_foo
{
    template<typename... Args>
    aligned_foo(Args&&... args) 
    {
        //How to constexpr construct foo?
        data_ptr = ::new((void*)::std::addressof(storage)) foo(std::forward<Args>(args)...);
    }
    std::aligned_storage<sizeof(foo)> storage;
    foo* data_ptr;
};

int main()
{
    aligned_foo("Hello", 0.5);
}

No.不能出现在常量表达式中的一长串表达式之一是新表达式

实现变体并使其constexpr友好的唯一方法是使用联合。虽然,即使使用联合,您仍然无法拥有可以包含fooconstexpr友好变体,因为它不是文字类型(通过它具有非平凡析构函数的方式,通过std::string具有非平凡析构函数的方式)。