【发布时间】:2017-09-04 09:59:16
【问题描述】:
我想知道是否有类似 std::get 的东西可以在编译时访问任何 n 维数组。例如。 get_value(arr, 1,2,3) 应返回值 arr[1][2][3]。我尝试使用递归模板 constexpr。但是,类型推导似乎有问题。
#include <iostream>
#include <string>
#include <array>
template <class T, class FIRST, class ... REST>
constexpr auto get_value(T arr, FIRST first, REST... rest) {
auto sub = arr[first];
using sub_t = decltype(sub);
return get_value<sub_t, REST...>(sub, rest...);
}
// works for 1D
template<class T>
constexpr auto get_value(T arr, auto first) {
return arr[first];
}
int main()
{
using arr1_t = std::array<int, 5>;
using arr2_t = std::array<arr1_t, 5>;
arr1_t arr1 = {1,2,3,4,5};
arr2_t arr2 = {arr1, arr1, arr1, arr1, arr1};
std::cout << get_value(arr1, 1) << std::endl;
std::cout << get_value(arr2, 1,1) << std::endl;
}
【问题讨论】:
-
你的阵列是什么样的?它真的是多维的
arr[0][1][2]还是用作多维的一维数组? -
我更新了问题,真的是[][][]..
-
我认为有必要将 [] 运算符推广到参数包的需要:/
标签: c++ c++11 templates template-meta-programming