我有这种情况:
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/