【发布时间】:2017-10-28 10:57:17
【问题描述】:
我正在尝试创建一个对齐的变体类型,它使用 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);
}
【问题讨论】:
-
std::string没有constexpr构造函数,所以不太可能。 -
简答:否。长回答: 可能的原因之一:类类型的对象的生命周期从其构造函数具有完全的。对于
constexpr上下文,管理此类生命周期的唯一合理方法是使用自动存储持续时间 或静态存储持续时间 的对象 - 因为编译器可以轻松推断这些生命周期。也许当我们的编译器变得像 Rust 一样强大时,我们可以在这方面做得更好