【发布时间】:2015-02-08 05:18:26
【问题描述】:
我正在尝试编写一个模板函数,该函数利用数组的长度,只给出引用。我知道以下代码有效
template <unsigned S>
void outputArray(int (&a)[S]) {
// S = length of array
}
int main() {
int a[6] = {0};
outputArray(a);
}
我现在尝试通过使用动态分配的数组来扩展它。我很确定这是不可能的,因为前一种情况下的数组大小是在编译时确定的,但我可能是错的。
void readFile(int*) {
int a_temp[MAX_DATA]; // MAX_DATA is predefined constant
int length;
// a_temp and length assigned from file
a = new int[length];
memcpy(a, &a_temp, sizeof(int)*length);
}
template <unsigned S>
void outputArray(int (&a)[S]) {}
int main() {
int* a;
readFile(a);
outputArray(a); // This is where my problem lies --- Mismatched types
}
当然,不相关的逻辑会被截断。正如您在 readFile 函数中看到的那样,我正在从文件中读取可变长度数组。但是,我不知道如何使用指针将数组作为 int [S] 类型传递给 outputArray 函数。
我仅限于使用数组(没有 C++ 向量),因为这是一项家庭作业。如果我绝对无法将指针作为int [S] 类型传递,那么我将采用简单的方法,让 readFile 函数返回数组长度的值。
【问题讨论】: