在为std::array 定义专门化是否安全std::array
中,提问者询问专门化具有昂贵的默认构造函数的程序定义类型是否安全。目标是std::array
使用廉价的方法来初始化 中的所有元素构造函数而不是默认构造函数来初始化 中的所有元素。
我现在并不质疑这个设计。我很好奇这种可能性,对于这个问题,我建议在聚合初始化时使用大括号省略,定义一个内部类并通过标签使用特殊的构造函数:
namespace foo {
struct cheap_tag_t {};
inline constexpr cheap_tag_t cheap_tag;
class bar {
public:
inline bar() { std::cout << "expensive ctor\n"; }
inline bar(int) { std::cout << "int ctor\n"; }
inline bar(cheap_tag_t) { std::cout << "cheap ctor\n"; }
};
} // namespace foo
Run Code Online (Sandbox Code Playgroud)
template <std::size_t N>
requires (N != 0) // let the standard array take care of N==0
struct std::array<foo::bar, N> {
struct inner_array { …
Run Code Online (Sandbox Code Playgroud)