2017-10-28 56 views
0

我正在尝试使用std :: aligned_storage来保存数据的对齐变体类型。有没有一种方法可以用constexpr的方式构建一个对象?我读过你不能做constexpr安置新的。C++ constexpr in place aligned storage construction

#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); 
} 
+0

'std :: string'没有'constexpr'构造函数,所以不太可能。 –

+2

**简答:**否**长答案:**其中一个可能的原因:类类型的对象的生命周期在其构造函数完成时开始。对于'constexpr'上下文来说,管理这种生命周期的唯一有效方法是使用*自动存储持续时间*或*静态存储持续时间*的对象 - 因为编译器可以轻松推理这些生命周期。也许当我们的编译器像Rust一样有能力时,我们可以在这方面做得更好 – WhiZTiM

回答

0

expressions长列表的一个号不能出现在常量表达式是一个new-expression

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