我正在尝试将2D数组传递给函数。不幸的是,我坚持使用相当老的编译器(gcc-4.1),不能使用任何现代方法。经过一些谷歌搜索和堆栈讨论流程。我想到了这个。 MatrixMN is own implementation of matrices
namespace MatrixMNTest {
// Test variables
double matrix_4X2[4][2] = {{1, 2}, {3, 4}, {11, 12}, {0, 1}};
template <size_t size1, size_t size2>
MatrixMN getMatrix(const double (&arr)[size1][size2]) {
MatrixMN m(size1, size2);
for (unsigned i = 0; i < size1; ++i) {
for (unsigned j = 0; j < size2; ++j) {
m(i, j) = arr[i][j];
}
}
return m;
}
}
int main() {
size_t size1 = 4;
size_t size2 = 2;
// success
math::MatrixMN A = MatrixMNTest::getMatrix(MatrixMNTest::matrix_4X2);
double scalar = 2.5;
double result[size1][size2];
memcpy(result, MatrixMNTest::matrix_4X2, sizeof(result));
// fail
math::MatrixMN B = MatrixMNTest::getMatrix(result);
}
我试图在gcc-4.1和7.5.0上运行相同的代码以检查错误消息
gcc-4.1
error: no matching function for call to 'getMatrix(double [(((unsigned int)(((int)size1) - 1)) + 1u)][(((unsigned int)(((int)size2) - 1)) + 1u)])'
gcc-7.5.0
test.cpp: In function ‘int main()’:
test.cpp:96:52: error: no matching function for call to ‘getMatrix(double [size1][size2])’
math::MatrixMN B = MatrixMNTest::getMatrix(result);
^
test.cpp:69:16: note: candidate: template<long unsigned int size1, long unsigned int size2> math::MatrixMN MatrixMNTest::getMatrix(const double (&)[size1][size2])
math::MatrixMN getMatrix(const double (&arr)[size1][size2]) {
^~~~~~~~~
test.cpp:69:16: note: template argument deduction/substitution failed:
test.cpp:96:52: note: variable-sized array type ‘long int’ is not a valid template argument
math::MatrixMN B = MatrixMNTest::getMatrix(result)
不确定。如何解决此问题。 任何帮助将不胜感激。
答案 0 :(得分:0)
我将代码修改为..
const size_t size1 = 4;
const size_t size2 = 2;
double result[size1][size2];
或直接传递它们。
double result[4][2];