問題描述
當(dāng)我嘗試在 gcc 4.8.2 中編譯以下代碼時,出現(xiàn)以下錯誤:
<塊引用>test.cc: 在函數(shù)‘void foo(int*)’中:test.cc:15:16: 錯誤:沒有匹配的函數(shù)調(diào)用‘begin(int*&)’for (int i : bar) {^
以及來自模板庫深處的其他一些人.
#include 使用命名空間標(biāo)準(zhǔn);void foo(int*);int main() {int bar[3] = {1,2,3};for (int i : bar) {cout<<我<<結(jié)束;}富(酒吧);}void foo(int* bar) {for (int i : bar) {cout<<我<<結(jié)束;}}
如果我重新定義 foo
以使用索引的 for 循環(huán),那么代碼會編譯并按預(yù)期運行.此外,如果我將基于范圍的輸出循環(huán)移動到 main
中,我也會得到預(yù)期的行為.
如何將數(shù)組 bar
傳遞給 foo
使其能夠在其上執(zhí)行基于范圍的 for 循環(huán)?
隨著數(shù)組衰減變成一個指針,你'丟失了一條重要信息:它的大小.
使用數(shù)組引用,您的基于范圍的循環(huán)可以工作:
void foo(int (&bar)[3]);int main() {int bar[3] = {1,2,3};for (int i : bar) {cout<<我<<結(jié)束;}富(酒吧);}void foo(int (&bar)[3]) {for (int i : bar) {cout<<我<<結(jié)束;}}
或者,以通用方式(即在函數(shù)簽名中不指定數(shù)組大小),
模板void foo(int (&bar)[array_size]) {for (int i : bar) {cout<<我<<結(jié)束;}}
試試
When I try to compile the following code in gcc 4.8.2, I get the following error:
test.cc: In function ‘void foo(int*)’: test.cc:15:16: error: no matching function for call to ‘begin(int*&)’ for (int i : bar) { ^
Along with a bunch of others from deeper in the template library.
#include <iostream>
using namespace std;
void foo(int*);
int main() {
int bar[3] = {1,2,3};
for (int i : bar) {
cout << i << endl;
}
foo(bar);
}
void foo(int* bar) {
for (int i : bar) {
cout << i << endl;
}
}
If I redefine foo
to use an indexed for loop, then the code compiles and behaves as expected. Also, if I move the range-based output loop into main
, I get the expected behaviour as well.
How do I pass the array bar
to foo
in such a way that it is capable of executing a range-based for-loop on it?
With the array decaying into a pointer you're losing one important piece of information: its size.
With an array reference your range based loop works:
void foo(int (&bar)[3]);
int main() {
int bar[3] = {1,2,3};
for (int i : bar) {
cout << i << endl;
}
foo(bar);
}
void foo(int (&bar)[3]) {
for (int i : bar) {
cout << i << endl;
}
}
or, in a generic fashion (i.e. without specifying the array size in the function signature),
template <std::size_t array_size>
void foo(int (&bar)[array_size]) {
for (int i : bar) {
cout << i << endl;
}
}
Try it out
這篇關(guān)于傳遞給非主函數(shù)的數(shù)組上基于范圍的 for 循環(huán)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!