使用模板将可变长度的2D数组传递给函数
Passing variable-length 2D array to functions using template
下面是我遇到的问题的一个例子:
#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]
}
你也可以在这里找到一些更有用的资源!
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何打印 2D 字符数组C++
- 如何将数组 2d 作为参数从函数传递并返回数组 2d 此函数
- 数组 2D 多个值
- 创建数组数组 (2D),而无需在 Java 中初始化内部数组
- 如何在C++中将文本文件传输到数组2D
- 从同一类的另一个方法调用数组2D-C++
- 获取地址在数组2d中的位置