c++ - 是否有用于从另一个不同的 std::array 初始化 std::array 的特定语法?

标签 c++ arrays stl initialization

我有这种情况:

class A {
    ...
};

class B {
    public:
        B(A x) { .... }
}

std::array<A, some_constant_value> init;
std::array<B, some_constant_value> arr = {
    init[0], 
    init[1],
    init[2],
    ...... ,
    init[some_constant_value-1]
};

是否有比这更好的语法来避免输入所有元素? (这不需要干预 some_constant_value 会改变的机会吗?)

最佳答案

我有这段代码。我想这就是你想要的:

  template<unsigned... Indices>
  struct indices {
    using next = indices<Indices..., sizeof...(Indices)>;
  };

  template<unsigned N>
  struct build_indices {
    using type = typename build_indices<N-1>::type::next;
  };
  template<>
  struct build_indices<0> {
    using type = indices<>;
  };

  namespace impl {
    template<typename To, typename From, unsigned... Is>
    std::array<To, sizeof...(Is)>
    array_convert_impl(std::array<From, sizeof...(Is)> const& from, indices<Is...>) {
      return std::array<To, sizeof...(Is)>{{ from[Is]... }}; 
    }
  } // namespace impl
  template<typename To, typename From, unsigned N>
  std::array<To, N>
  array_convert(std::array<From, N> const& from) {
    return impl::array_convert_impl<To>(from, typename build_indices<N>::type());
  }

然后你可以这样做:

std::array<B, some_constant_value> arr = array_convert<B>(init);

关于c++ - 是否有用于从另一个不同的 std::array 初始化 std::array 的特定语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16266815/

相关文章:

c++11 - STL map::insert 是否应该支持 move_iterators 的 move 语义?

c++ - clang:单行注释中用空格分隔的反斜杠和换行符

c++ - Libcurl - cookie 身份验证

c++ - 无法使用 MinGW 在 Linux 上为 Windows 构建

c++ - std::find 使用用户定义的结构

php - 选择数据然后从数组中匹配

c++ - dijkstra_shortest_paths Boost Graph Lib 1.57.0 失败

html - HTML 表单数组中的方括号。只是常规的还是有意义的?

c++ - 使用和不使用 SSE 的不同结果( float 组乘法)

c++ - 如何在C++中实现一个唯一id的队列,其中元素可以是 "bumped"到顶部?