c++ - C++ constexpr就地对齐存储结构

标签 c++ c++14 variant

我正在尝试使用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);
}

最佳答案

不能。在常量表达式中不能出现的一长串expressionsnew-expression

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

关于c++ - C++ constexpr就地对齐存储结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988947/

相关文章:

c++ - 使用 C++ 将图像写入 RabbitMQ 队列

C++ 标准列表和默认可构造类型

c++ - 如何使用列表初始化对聚合类型进行值初始化

c++ - std::vector 和 _variant_t 之间的转换

c++ - 类变体类型 : Why a vtable?

c++ - Stroustrup 书中的前后条件

C++:混合:boost::any + typeid + pointer:克隆 'generic' 值,如果它是一个指针

c++ - 在没有动态内存的世界中我需要虚拟析构函数吗?

c++ - const 临时类型的最佳实践

c++ - 如何将字符串数组转换为 SAFEARRAY 或 VARIANT 或 COleVariant?