不,但是您可以使用以下命令相当轻松地手动完成指数技巧 http://loungecpp.wikidot.com/tips-and-tricks:indices,假设实现提供constexpr
std::get
(或等效地constexpr
超载的operator[]
):
#include <iostream>
#include <array>
#include <type_traits>
// http://loungecpp.wikidot.com/tips-and-tricks%3aindices
template <std::size_t... Is>
struct indices {};
template <std::size_t N, std::size_t... Is>
struct build_indices: build_indices<N-1, N-1, Is...> {};
template <std::size_t... Is>
struct build_indices<0, Is...>: indices<Is...> {};
template<typename T, typename U, size_t i, size_t... Is>
constexpr auto array_cast_helper(
const std::array<U, i> &a, indices<Is...>) -> std::array<T, i> {
return {{static_cast<T>(std::get<Is>(a))...}};
}
template<typename T, typename U, size_t i>
constexpr auto array_cast(
const std::array<U, i> &a) -> std::array<T, i> {
// tag dispatch to helper with array indices
return array_cast_helper<T>(a, build_indices<i>());
}
int main() {
static constexpr std::array<double, 3> darray{{1.5, 2.5, 3.5}};
static constexpr std::array<int, 3> iarray = array_cast<int>(darray);
}
如果您的实现没有提供constexpr
get
or operator[]
,你不能使用array
因为当前没有访问数组元素的标准方法constexpr
;你最好的选择是使用你自己的实现array
与constexpr
扩展。
The constexpr
建议添加库以添加到标准中n3470 http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3470.html.