C++ constexpr 到位对齐的存储结构
C++ constexpr in place aligned storage construction
我正在尝试制作一个对齐的变体类型,该变体类型使用 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
友好的唯一方法是使用联合。虽然,即使使用联合,您仍然无法拥有可以包含foo
的constexpr
友好变体,因为它不是文字类型(通过它具有非平凡析构函数的方式,通过std::string
具有非平凡析构函数的方式)。
相关文章:
- 访问存储在向量C++中的结构的多态成员
- 带结构的二维矢量:如何存储元素
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 哪些存储了不完整类型的 STL 数据结构可以用作类成员?
- 如何避免在数据结构中包含存储为字段的类?
- 如何使用 redis-plus-plus 存储二进制数据,就像我想存储结构一样?@for_stack?
- C++:对象将 lambda 存储到结构中,稍后调用该函数
- 将载体和cv :: mat to Disk的存储结构 - C 中的数据序列化
- 存储结构的更好方法
- Boost::序列化存储结构时的堆栈溢出错误
- 在类存储结构中使用动态分配的数组
- C++ constexpr 到位对齐的存储结构
- 用于存储结构对象的队列
- 如何在C++数组中存储结构数据
- 在矢量中存储结构信息(文本 RPG 游戏)
- 存储结构矢量的最佳方式
- 存储结构体的向量
- 在堆栈中存储结构体
- 在数组中存储结构(c++)
- 为什么这种自动存储结构仍然存在