按引用传递未知级别的阵列 [英] Pass array of unknown rank by reference

查看:103
本文介绍了按引用传递未知级别的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过引用传递未知的维数(级)的数组。基本上,我想要做这样的事情(不编译)

I am trying to pass by reference an array of unknown number of dimensions (rank). Basically, I'd like to do something like this (which does not compile)

template <typename T, int... dims>
void f(T (&arr)[dims]...) // not working
{
    // would like to modify the elements of `arr` here, according to some rule
}

int main()
{
    int arr[2][3][4]; // rank 3
    f(arr);
}

是否有实现这一目标的方法吗?尤其是它在某种程度上可以使用可变参数模板的方法呢?

Is there any way of achieving this? In particular, is it somehow possible to use a variadic-template approach?

我可以做普通的模板&LT; typename的T&GT; F(T&安培; ARR),但在这种情况下,我怎么会是能够恢复的大小没有明确地传递他们? (即使有一个可变参数模板的方法我不知道如何恢复包中的各个元素......没有某种递归折叠)。

I can do the generic template<typename T> f(T& arr), but in this case how I'd be able to recover the sizes without explicitly passing them? (Even with a variadic template approach I'm not sure how to recover the individual elements in the pack... without some kind of recursive folding).

在特定的,我正在寻找初始化根据一些规则未知秩阵列的简单方法。

In particular, I'm looking for a simple way of initializing an unknown-rank array according to some rule.

推荐答案

您只传递一个引用类型 T 的数组。然后 T 可以是另一个数组等等。不需要复杂的语法。所以,你的code将是这样的:

You just pass an reference to array of type T. Then T can be another array and so on. No need for complex syntax. So your code will look like this:

template <typename T, int sz>
void f(T (&arr)[sz]) // working
{
    std::rank<T[sz]>::value; //evaluates to array rank
}

int main()
{
    int arr[2][3][4]; // rank 3
    f(arr);
}

然后,您可以使用 的std ::排名

和则可以通过使用 <$ C $获取子数组大小C>的std :: remove_extent 和模板递归。

And you can get sub-array sizes by using std::remove_extent and template recursion.

例如。

这篇关于按引用传递未知级别的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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