C ++ constexpr就地对齐存储结构 [英] C++ constexpr in place aligned storage construction
问题描述
我试图创建一个使用std :: aligned_storage来保存数据的对齐变体类型.有没有办法以constexpr的方式构造对象?我读到你不能做新的constexpr放置.
#include< iostream>#include< string>结构foo{foo(std :: string a,float b):bar1(a),bar2(b){}std :: string bar1;浮条2;};结构aligned_foo{template< typename ... Args>aligned_foo(Args& ... args){//如何用constexpr构造foo?data_ptr = :: new((void *):: std :: addressof(storage))foo(std :: forward< Args>(args)...);}std :: aligned_storage< sizeof(foo)>贮存;foo * data_ptr;};int main(){aligned_foo("Hello",0.5);}
否.表达式的一长串列表之一,它们不能出现在常量中表达式是 新表达式 ./p>
实现变体并使它对 constexpr
友好的唯一方法是使用联合.尽管即使有一个联合,您仍然不能拥有一个 constexpr
友好的变体,它可以包含一个 foo
,因为它不是文字类型(通过它具有非平凡的析构函数,例如通过 std :: string
具有非平凡的析构函数).
I'm trying to make an aligned variant type that uses std::aligned_storage to hold the data. Is there a way to construct an object in place in a constexpr way? I read you can't do constexpr placement new.
#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. One of the long list of expressions that can't appear in a constant expression is a new-expression.
The only way to implement a variant and have it be constexpr
-friendly is through the use of a union. Although, even with a union, you still wouldn't be able to have a constexpr
-friendly variant that can contain a foo
since it's not a literal type (by way of it having a non-trivial destructor, by way of std::string
having a non-trivial destructor).
这篇关于C ++ constexpr就地对齐存储结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!