【问题标题】:variadic multidimensional array可变多维数组
【发布时间】:2013-05-16 13:17:23
【问题描述】:

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

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. 

通过可变参数模板的帮助

代替:

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

【问题讨论】:

  • 你想创建一个数组,还是从中获取一个元素?
  • 更多细节或用例会很有帮助。不太清楚你为什么/你想做什么。

标签: c++ templates multidimensional-array variadic-templates


【解决方案1】:

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

它适用于plain arraysstd::arrays。您可以通过复制专业化来扩展它std::vector。 (我认为它应该适用于任何重载 operator[] 但不确定的东西。


#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

Here is a test run.


我没有将autotrailing return types 一起使用,因为indexed 的可变参数版本在推断返回类型时不会匹配自身。因此,在 gcc 解决之前,您将不得不使用类似的东西。

【讨论】:

  • 非常感谢,很好的解决方案。
  • @Avatar 很高兴它有帮助。其实我什至可以自己使用它。比在生成的代码中一直执行 [][] 更容易。所以也感谢你提出这个想法:)
【解决方案2】:

你可以重载 operator()。我不确定它是否会对你有很大帮助。

如果您使用的是 C++11,您可能会创造性地考虑使用 initializer_list。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-17
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2017-05-16
    • 2011-10-26
    • 2021-10-31
    相关资源
    最近更新 更多