可变多维数组 [英] variadic multidimensional array

查看:35
本文介绍了可变多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以调用一个多维数组吗

Could I call a multidimensional array like

func(0,0,0); //=> if I know it's dimension on the run time. 
func(0,0,0,0,0,0,0,0,0,0,0); //=> if I know it's dimension on the run time. 

通过可变参数模板的帮助

through help of the variadic templates

代替:

data[0][0][0];
data[0][0][0][0][0][0][0][0][0][0][0];

推荐答案

这应该可行,但您必须使用 indexed 而不是执行 data[1][2][3](data,1,2,3)

This should work but instead of doing data[1][2][3] you will have to use indexed(data,1,2,3)

它适用于普通数组以及std::arrays.您可以通过复制特化来扩展它 std::vector.(我认为它应该适用于任何重载 operator[] 但不确定的事情.)

It works for plain arrays as well as std::arrays. You can extend it std::vector just by duplicating the specializations. (I think it should work for any thing that overloads operator[] but not sure.)

#include <iostream>
#include <array>

template<typename T, size_t dim>
struct getTypeAtDim { typedef T type; };

template<typename T, size_t N>
struct getTypeAtDim<T[N],1> { typedef T type; };

template<typename T, size_t dim, size_t N>
struct getTypeAtDim<T[N],dim> : getTypeAtDim< T, dim-1> {};

template<typename T, size_t N>
struct getTypeAtDim<std::array<T,N>,1> { typedef T type; };

template<typename T, size_t dim, size_t N>
struct getTypeAtDim<std::array<T,N>,dim> : getTypeAtDim< T, dim-1> {};

template<typename T, size_t dim>
using typeAtDim = typename getTypeAtDim<T, dim>::type;

template<typename T> 
typeAtDim<T,1>&
indexed(T& arr, const int& first) {
    return arr[first];
}

template<typename T, typename... Args> 
typeAtDim<T,sizeof...(Args) + 1>& 
indexed(T& arr, const int& first, const Args& ...rest) {
    return indexed(arr[first],rest...);
}

<小时>

int main() {
    std::array<int,2> a1 = {1,2};
    std::array<int,2> a2 = {3,4};
    std::array<std::array<int,2>,2> a = {a1,a2};
    std::array<std::array<std::array<int,2>,2>,2> c = {a,a};
    int b[2][2] = {{5,6},{7,8}};


    std::cout << indexed(a,1,1) << std::endl;
    indexed(a,1,1) = 5;
    std::cout << indexed(a,1,1) << std::endl;
    std::cout << indexed(b,1,1) << std::endl;
    std::cout << indexed(c,1,1,1) << std::endl;
    indexed(c,1,1) = a1;
    std::cout << indexed(c,1,1,1) << std::endl;
}

<小时>

4 5 8 4 2

<小时>

代码是代码a207代码是低测试/strong>.


Here is a test run.

我没有将 autotrailing return types 一起使用,因为 indexed 的可变参数版本在推导类型时将与自身不匹配的回报.因此,在使用 gcc 解决此问题之前,您将不得不使用类似的方法.

I am not using auto with trailing return types because the variadic version of indexed will not match itself when deducing the type of the return. So until that gets resolved with gcc you will have to use something like this.

这篇关于可变多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆