c++ - Overloading (c)begin/(c)end -


i tried overload (c)begin/(c)end functions class able call c++11 range-based loop.

it works in of cases, don't manage understand , solve 1 :

for (auto const& point : fprojectdata->getpoints()){ ... } 

this line returns error:

error c2662: 'mycollection<t>::begin' : cannot convert 'this' pointer 'const mycollection' 'mycollection<t> &' 

because fprojectdata pointer const. if make non-const, work. don't understand why, considering cbegin() & cend() developped exactness begin() & end() functions.

here functions developped (in header file) in mycollection:

/// \returns begin iterator typename std::list<t>::iterator begin() {     return objects.begin(); }  /// \returns begin const iterator typename std::list<t>::const_iterator cbegin() const {     return objects.cbegin(); }  /// \returns end iterator typename std::list<t>::iterator end() {     return objects.end(); }  /// \returns end const iterator typename std::list<t>::const_iterator cend() const {     return objects.cend(); } 

any ideas?

a range-based loop (for class-type range) looks begin , end functions. cbegin , cend not considered @ all:

§ 6.5.4 [stmt.ranged]/p1 *:

[...]

  • if _ranget class type, unqualified-ids begin , end looked in scope of class _ranget if class member access lookup (3.4.5), , if either (or both) finds @ least 1 declaration, begin-expr , end-expr __range.begin() , __range.end(), respectively;

  • otherwise, begin-expr , end-expr begin(__range) , end(__range), respectively, begin , end looked in associated namespaces (3.4.2). [ note: ordinary unqualified lookup (3.4.1) not performed. — end note ]

for const-qualified range related member functions must const-qualified (or should callable const-qualified instance if latter option in use). you'd need introduce additional overloads:

typename std::list<t>::iterator begin() {     return objects.begin(); }  typename std::list<t>::const_iterator begin() const { //                                            ~~~~^     return objects.begin(); }  typename std::list<t>::const_iterator cbegin() const {     return begin(); }  typename std::list<t>::iterator end() {     return objects.end(); }  typename std::list<t>::const_iterator end() const { //                                          ~~~~^     return objects.end(); }  typename std::list<t>::const_iterator cend() const {     return end(); } 

demo


* wording comes c++14, differences unrelated problem stated


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -

Nuget pack csproj using nuspec -