函数参数上的分号
Semicolon on a function parameters
matrix_* matrix_insert_values(int n; double a[][n], int m, int n)
{
matrix_* x = matrix_new(m, n);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
x->v[i][j] = a[i][j];
return x;
}
我的测试矩阵示例
double in[][3] = {
{ 12, -51, 4},
{ 6, 167, -68},
{ -4, 24, -41},
{ -1, 1, 0},
{ 2, 0, 3},
};
我有点迷路了,我不知道int n;
在我的参数声明中是什么,它在C上工作,但c++不允许这种实现。我想了解这是如何工作的,因为我要把这段代码迁移到c++。
这是C99 GNU扩展(GCC文档)中很少使用的特性,用于前向声明VLA声明器中使用的参数。
matrix_* matrix_insert_values(int n; double a[][n], int m, int n);
你看到int n
出现了两次吗?第一个int n;
只是实际的int n
的前向声明,它在最后。它必须出现在double a[][n]
之前,因为a
的声明中使用了n
。如果你愿意重新排列参数,你可以把n
放在a
之前,这样你就不需要这个特性了
matrix_* matrix_insert_values_rearranged(int m, int n, double a[][n]);
c++兼容性注意事项
要清楚,GNU扩展只是函数参数的前向声明。下面的原型是标准C:
// standard C, but invalid C++
matrix_* matrix_insert_values_2(int m, int n, double a[][n]);
不能从c++中调用这个函数,因为这段代码使用了可变长度数组,在c++中是不支持的。为了能够从c++中调用它,您必须重写该函数。
如果你总是这样在C中调用它(即n和m在编译时固定),那么在c++中你可以这样做:
template <int N, int M>
void matrix_insert_values(const double (&a)[M][N]);
int main() {
double in[5][3] = {
{ 12, -51, 4},
{ 6, 167, -68},
{ -4, 24, -41},
{ -1, 1, 0},
{ 2, 0, 3},
};
matrix_insert_values(in);
};
以N和M作为模板参数,这些参数在编译时从传递给函数的输入中自动推导出来。
相关文章:
- 将可变参数函数的参数封装在类实例中
- QML 使用带有参数C++函数
- 使用可变参数函数作为模板参数
- 如何在C++中伪造虚拟可变参数函数模板?
- 为什么可变参数函数不适用于模板
- C++ std::functional 中的可变参数函数模板
- 可变参数函数指针的定义对于VxWorks spyLib来说不清楚
- 使用可变参数函数覆盖具有不同函数签名的虚函数
- 考虑引用和常量的可变参数函数包装器
- 使用可变参数函数将整数和/或整数数组放入单个 int 数组中
- 在可变参数函数中转发特定范围的参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 使用带有一个参数函数的递归找到数字的平方
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 多个可变参数函数的单个模板参数包?
- 参数数据类型未知的可变参数函数
- 可变参数函数参数包扩展
- 使用模板可变参数函数将多个参数传递给另一个函数
- 对可变参数函数的递归调用的链接器错误
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类