c++ - 从另一个 constexpr std::array 初始化没有默认构造函数的对象的 std::array

标签 c++ templates c++14 constexpr stdarray

是否可以初始化一个对象数组,其成员是从另一个普通对象的 constexpr 数组初始化的。例如我有以下内容

struct X
{
  X(int y): _x(y){}
  int _x;
};

struct Z
{
  static constexpr std::array<int, 4> arr = {1,6,0,4};
  

  // How does one implement make_array below that constructs
  // X[0] from arr[0], X[1] from arr[1], etc.
  // Is it even feasible in C++14/17?
  std::array<X, arr.size()> xArr = make_array(  );  

};

最佳答案

使用std::index_sequence:

template <typename T, typename U, std::size_t N, std::size_t ... Is>
constexpr std::array<T, N> make_array(const std::array<U, N>& a, std::index_sequence<Is...>)
{
    return {{T(a[Is])...}};
}

template <typename T, typename U, std::size_t N>
constexpr std::array<T, N> make_array(const std::array<U, N>& a)
{
    return make_array<T>(a, std::make_index_sequence<N>());
}

用法:

static constexpr std::array<int, 4> arr = {1,6,0,4};
  
/*constexpr*/ std::array<X, arr.size()> xArr = make_array<X>(arr);  

Demo

关于c++ - 从另一个 constexpr std::array 初始化没有默认构造函数的对象的 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65600141/

相关文章:

c++ - C++ 中运算符 = 的操作数的顺序是怎样的?

c++ - boost asio 类似信号量的解决方案

c++ - 为什么链接器不提示重复的符号?

C++:如何要求一种模板类型派生自另一种

C++模板类继承和运算符使用

c++ - 哪种处理虚拟析构函数的方法更好?

c++ - 是否允许编译器省略对指针的 &* 运算符的组合调用?

c++ - std::vector 到 std::span<T> 的转换

c++ - 简单的 C++ 错误, "else without previous if"

c++ - 如何在结构中连接 std::is_same