我正在尝试使用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);
}
最佳答案
不能。在常量表达式中不能出现的一长串expressions是new-expression。
实现变体并使它对constexpr
友好的唯一方法是使用联合。尽管即使有一个联合,您仍然无法拥有一个constexpr
友好型变量,它可以包含foo
,因为它不是文字类型(通过它具有非平凡的析构函数,通过std::string
具有非平凡的析构函数)。
关于c++ - C++ constexpr就地对齐存储结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988947/