使用模板将可变长度的2D数组传递给函数

Passing variable-length 2D array to functions using template

本文关键字:数组 2D 函数      更新时间:2024-09-27

下面是我遇到的问题的一个例子:

#include <stdio.h>
#include <iostream>
template<std::size_t U, std::size_t V>
void func2(int (&twoDArrayA)[U][V], const int shift){
const int length = 1 << shift;
int twoDArrayB[length][length]; //Successful
}
//template<std::size_t A> <-- Tried to solve the problem by adding this
void func1(const int shift){
const int length = 1 << shift;
int twoDArrayA[length][length]; //Failed
func2(twoDArrayA,shift);
}
int main() {
const int shift = 3;
func1(shift);
}

错误消息:

错误:对"func2(int[length][length],const int&("的调用没有匹配的函数模板参数推导/替换失败:可变大小的数组类型"int"不是有效的模板参数

我认为这是因为在func2之前使用了模板,所以我尝试在func1上做同样的事情。尝试调用func1失败。错误消息:

错误:调用'func1(const int&('没有匹配的函数模板参数推导/替换失败:无法推导模板参数"A">

有什么方法可以将twoDArrayA这样的参数传递给func2吗?

func2无法推导出数组大小,因为在编译时未知;length是在运行时根据传递给func1的参数决定的。为了使用模板参数和推导的传递引用,您需要在编译时有一个定义大小的2D数组,例如int arr[8][8]

看起来您正在编写的代码想要根据shift决定func1中的数组大小,然后将该数组传递给func2。根据1<<shift:的结果,您可以考虑将func2设计为采用int**,然后像访问2D阵列一样访问它

void func2(int** twoDArrayA, const int shift) {
const int length = 1 << shift;
int last_item = twoDArrayA[length-1][length-1]
}

你也可以在这里找到一些更有用的资源!