gpt4 book ai didi

c++ - 将模板用作数组维度时模板如何工作?

转载 作者:行者123 更新时间:2023-12-03 07:37:16 24 4
gpt4 key购买 nike

我尝试使用模板作为数组维度值。当试图将错误的维度指定为模板参数时,我感到很困惑。例如代码:

#include <iostream>

using namespace std;

template <int X, int Y>
void f(int a[X][Y]) {
for (int i = 0; i < X; ++i) {
for (int j = 0; j < Y; ++j) {
cout << a[i][j] << " ";
}
cout << '\n';
}
}

int main() {
int a[2][2] = {{1, 2}, {3, 4}};
f<2, 2>(a); // compilation succeeded
f<10, 2>(a); // compilation succeeded
f<2, 10>(a); // compilation FAILED
}

为什么在最后一个案例中编译失败,而在 <10, 2> 中却没有?

error: no matching function for call to 'f'
note: candidate function template not viable: no known conversion from 'int [2][2]' to 'int (*)[10]' for 1st argument

最佳答案

你得到这个结果是因为 f(int a[X][Y]) 是一个谎言<​​/strong>。

数组在 C++ 中不是一等公民。您不能按值将数组作为函数参数传递。所以当你写这样的参数时,它被默默地调整为一个指针(仅限第一级)。因此 a 的类型实际上是 int (*)[Y]

因为 a 类型中没有 X,所以任何 X 都可以。

如果你想强制执行 XY,请尝试通过引用传递数组:

void f(int (&a)[X][Y])

或使用std::array

关于c++ - 将模板用作数组维度时模板如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65241072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com