我為基于范圍的回圈閱讀了此檔案:for
如果范圍型別有一個名為 begin 的成員和一個名為 end 的成員,則使用成員解釋。無論成員是型別、資料成員、函式還是列舉器,也不管其可訪問性如何,都會執行此操作。
class meow { enum { begin = 1, end = 2}; /* rest of class */ };因此,即使存在命名空間范圍的開始/結束函式,也不能將類似的類與基于范圍的 for 回圈一起使用。
我不明白這一段。成員解釋做了什么來禁止示例類與基于范圍的 for 回圈一起使用?
uj5u.com熱心網友回復:
“成員解釋”是指begin_expr并end_expr使用迭代型別的成員,而不是使用陣列或自由函式的普通偏移begin量end。
陣列解釋不在討論范圍內,因為它僅用于陣列。接下來考慮存在std::begin和std::end:
可以為未公開合適的 begin() 成員函式但可以迭代的類和列舉提供 begin 的自定義多載。
現在考慮這個例子:
#include <iostream>
#include <vector>
class meow {
enum { begin = 1, end = 2};
public:
std::vector<int> data;
};
// non-const iterators
auto begin(meow& m){ return m.data.begin(); }
auto end(meow& m) { return m.data.end(); }
// const iterators
auto begin(const meow& m){ return m.data.begin(); }
auto end(const meow& m) { return m.data.end(); }
int main() {
meow m;
for (const auto& e : m) {}
}
我們想要迭代meows data。但它不起作用。選擇成員解釋,即使meow::begin和mewo::end是私有的并且可以使用begin和函式。end因此錯誤:
<source>: In function 'int main()':
<source>:17:26: error: 'meow::<unnamed enum> begin' is private within this context
for (const auto& e : m) {}
^
<source>:5:12: note: declared private here
enum { begin = 1, end = 2};
^~~~~
<source>:17:26: error: 'begin' cannot be used as a function
for (const auto& e : m) {}
^
<source>:17:26: error: 'meow::<unnamed enum> end' is private within this context
<source>:5:23: note: declared private here
enum { begin = 1, end = 2};
^~~
<source>:17:26: error: 'end' cannot be used as a function
for (const auto& e : m) {}
^
當我們洗掉私有列舉時,該示例作業正常:
#include <iostream>
#include <vector>
class meow {
//enum { begin = 1, end = 2};
public:
std::vector<int> data;
};
// non-const iterators
auto begin(meow& m){ return m.data.begin(); }
auto end(meow& m) { return m.data.end(); }
// const iterators
auto begin(const meow& m){ return m.data.begin(); }
auto end(const meow& m) { return m.data.end(); }
int main() {
meow m;
for (const auto& e : m) {}
}
現場演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/425979.html
